c# - Destroying game object -


i have created simple 2d touch game in unity , have spikes spawning @ top of scene every 3 seconds , when spikes fall player tap spikes before hit characters below, however, when test game, when tap spike (game object) destroys of spikes (game objects) in scene. here code:

public gameobject spike; public float spawntime1 = 1f;  // use initialization void start () {     invokerepeating ("spawnspike", spawntime1, spawntime1);  }  // update called once per frame void update () {     (var = 0; < input.touchcount; ++i) {         if (input.gettouch(i).phase == touchphase.began) {             destroy (gameobject);         }     } }  void spawnspike () {      var newspike = gameobject.instantiate (spike);      newspike.transform.position = new vector3 (random.range(-3, 3), 11f, 0f); 

it looks you're destroying game-manager-like script when run

void update () {     (var = 0; < input.touchcount; ++i) {         if (input.gettouch(i).phase == touchphase.began) {             destroy (gameobject);         }     } } 

the line destroy (gameobject); destroying own game-object, i'm guessing parented spikes instantiated(?); hence destroying spikes @ once.

i suggest using raycasts find out if spike tapped on and/or spike tapped on, , destroying game-object of spike. here's reference. suggest looking tutorials regarding same if you're still finding hard understand.

i hope helps!

update:

here's sample code going:

    if (input.gettouch(i).phase == touchphase.began) {         vector3 pos = camera.main.screentoworldpoint (input.gettouch(i).position);         raycasthit2d hit = physics2d.raycast(pos, vector2.zero);         if (hit != null && hit.gameobject.comparetag("spike") && hit.collider != null) {             debug.log ("i'm tapping "+hit.gameobject.name);             destroy(hit.gameobject);         }     } 

this specific code require spike prefab (template) has tag "spike". suggest place code in kind of global "game-manager" script's update() (rather in spike script), don't over-process touches.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -