I’m very new to C#, and I have a OnCollisionEnter void detecting when the player collides with the object (a simple cube that’s been resized). I want to declare the object you collide with as a variable inside of the script, so I can later use it to start the animation on the collision. When I declare the cube as a GameObject, it says Animation isn’t part of it, which is the same with Transform. What type of variable would I declare this as so I can use Animation.Play()?
Hello. Sorry. if you are a noob, I am a super noob. Plus, I only know JavaScript :(. Maybe you can declare the object as boolean, so if collision is true, animation will take affect.
GameObject and Transform are the two base identifiers. A Transform is actually a component of GameObject but for all intents and purposes, all GO’s have a Transform so its just as easy to use it. As well as declaring variables, you can declare Types, which are the same really just have a lot more scope for holding custom information. If you make a script called MyScript, you can now also create a variable of type MyScript too. This is the basis for using Components.
But in your case as you wish to access a Component of on a particular gameObject called “Animation” you need to refer to it with GetComponent.
private GameObject myGO; //Create a gameobject variable;
void OnCollisionEnter (Collision col)
{
myGO = col.gameObject; //Your variable = the gameobject attached to the collision.
}
private Animation myAnim; //Here we declare a variable of Type 'Animation'. i.e a component
~~~~~
myAnim = myGO.GetComponent<Animation>(); //Here we populate the variable with a reference to an actual component.