- Home /
Get instance of the collider object
I'm new to Unity dev. So I have the character and the enemy, two objects in game. When one attacks other I can get it on event OnCollisionEnter. Great but my problem is that I don't know how I get the instance of the object that makes that collision.
Example: My character has attacked by the enemy. I can get the tag by collision.collider.tag
but I want to access it's instance for some properties and methods I have to call.
Note: I'm using C#.
collision.collider.gameObject - is this what you are looking for?
Or collision.collider.GetComponent< OneOfYourScripts>().someVariable etc...
@whydoidoit No man, this return a null reference exception...
@robertbu collision.collider.gameObject
will give me an object of gameObject type. I want an instance of my own object.
Answer by robertbu · Mar 17, 2013 at 04:53 PM
I'm assuming you want access to the component on the other game object. That is access to the public instance variables and public methods of the class you wrote and attached to the other game object. @whydoidoit's method above will work assuming the object you collided with has that script. If it does not, you will get a null reference. Take it a piece at a time to see what is going on. Substitute whatever tag you have for "Enemy" (or you can check the name). Or you can just do he GetComponent() and check to see that the return is not null.
void OnCollision(Collision collision) {
Debug.Log("Name: "+collision.collider.name+" Tag: "+collision.collider.tag);
if (collision.collider.tag == "Enemy") {
MyScript ms = collision.collider.GetComponent();
if (ms == null)
Debug.Log ("Script MyScript not attached to object");
else
ms.myVariable++;
}
}
@robertbu Sorry but compiler doesn't accepted the use of GetComponent()
without parameters. It throws this error: CS0411: The type arguments for method `UnityEngine.Component.GetComponent()' cannot be inferred from the usage. Try specifying the type arguments explicitly
For some reason, sometimes there is trouble using angle brackets in comments and everything between the brackets is removed. Replace the {} with angle brackets in the following text:
$$anonymous$$yScript ms = collision.collider.GetComponent{$$anonymous$$yScript}();
See @whydoidoit's example above as another example.
@robertbu include a space after every opening < angle bracket> and the parser will stop thinking it's an HT$$anonymous$$L command :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613094530im_/https://answers.unity.com/themes/thub/images/avi.jpg)