-5

It is a noob question, but Im starting dealing with programming, c# to be clear. So our teacher gave us this code:

var asteroid = collision.GetComponent\<AsteroidController\>();

if (asteroid != null)
{
    Destroy(asteroid.gameObject);
}

We are developing a game, so I have 4 scripts, Asteroid Controller, PlayerController and Bullet Controller

In Bullet Controller I have the code for player destroy the gameobject that has the script Asteroid Controller.

My question is, in wich script do I need to put thiis line of code.

I put the code in asteroidcontroller but is doing some errors enter image description here

gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • 1
    I'd recommend asking your teacher for guidance on the assignment. – Daniel Mann Mar 23 '22 at 20:37
  • Does this answer your question? [Collision detection not working unity](https://stackoverflow.com/questions/43939179/collision-detection-not-working-unity) – Ruzihm Mar 23 '22 at 20:43
  • @Ruzihm I don't think so .. OP has the code not even in the correct method which should probably be `OnCollisionEnter` ;) – derHugo Mar 24 '22 at 07:39

1 Answers1

1

So you are using the Unity Engine, the code will be different in different game engines.

In Unity's MonoBehaviour class there are a few functions that get called when special conditions are met. You can read more about what functions are called and when HERE.

Currently your code is under one of these functions Called Update which gets called every frame. For collisions you want to use a different function called OnCollisionEnter, you can read up on it HERE.

If we look at the function is looks something like this:

void OnCollisionEnter(Collision collision)
{
   ...
}

And as we can see it has a Collision parameter by default. Meaning your code will resolve and work:

void OnCollisionEnter(Collision collision)
{
    var player = collision.gameobject.GetComponent<PlayerController>();
    if (player != null)
    {
        Destroy(player.gameObject);
    }
}
CorrieJanse
  • 2,374
  • 1
  • 6
  • 23
  • There's also [some setup](https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html) for colliders on your objects. `Notes: Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached`. Unity doesn't check every object for collisions, only the things you tell it to check. That saves cpu overhead. – ps2goat Mar 23 '22 at 20:41