Search code examples
unity-game-engineunityscriptgameobject

Finding own gameobject (clone) from script


I am working on a piece of code here where I instantiate x amount of clones of a GameObject (prefab). There are several cars that are spawned randomly to simulate traffic, each clone are then attached a few scripts; one to control its AI, one to control collisions, and I want a 3rd one to destroy the car when it is "out of bounds", or too far out of the game for us to see it anymore.

Problem is, I have no idea how to access the GameObject the script is currently attached to. I managed to find any GameObject I am colliding with from the OnCollisionEnter2D, but I have not found a way to find "myself", or "itself".

I know I have a rigidbody2D attached, as I can control the car without instantiating or adding any components.

function FixedUpdate () 
{
    // Controls the velocity of the car
    rigidbody2D.angularVelocity = 0;
}

Any clues on how I can delete the aforementioned GameObject (including rigidbody2D) and stopping/deactivate all scripts attached to it?

I think I can destroy the GameObject (and everything attached to it) with "Destroy(GameObject)", just not sure how to set the GameObject correctly.

Edit: Also, it would be highly beneficial to know the name of the prefab used for that instance of the GameObject (different prefabs use the same scripts).


Solution

  • Well, every script has a property named "gameObject", which is the gameObject the script is currently attached to. So yes, your clue is right, you may just call Destroy (gameObject). If the script is attached to the object, the gameObject attribute is set by Unity

    [Edit] Doing so will also destroy every components (including scripts) attached to the object