what did i do wrong or did unity change it?
Unity changed. I’ve seen similar questions for the past few weeks. Although I don’t think they are duplicates but it would make sense to answer all these here for future questions.
The animation
variable is defined under Component
as a public
variable which MonoBehaviour
inherits from. Your code then inherits from MonoBehaviour
and you have access to animation
.
These are the complete list of variables from the Component
class that are deprecated:
public Component animation { get; }
public Component audio { get; }
public Component camera { get; }
public Component collider { get; }
public Component collider2D { get; }
public Component constantForce { get; }
public Component guiElement { get; }
public Component guiText { get; }
public Component guiTexture { get; }
public Component hingeJoint { get; }
public Component light { get; }
public Component networkView { get; }
public Component particleEmitter { get;
public Component particleSystem { get; }
public Component renderer { get; }
public Component rigidbody { get; }
public Component rigidbody2D { get; }
New way to access component that attached to the-same script:
Use GetComponent<ComponentName>()
. Capitalize the first letter of that variable to make it its component class. One exception is audio which becomes
AudioSource
instead of Audio.
1.animation.Play("Cube|moving side");
becomes GetComponent<Animation>().Play("Cube|moving side");
2.rigidbody2D.velocity
becomes GetComponent<Rigidbody2D>().velocity
3.rigidbody.velocity
becomes GetComponent<Rigidbody>().velocity
4.renderer.material
becomes GetComponent<Renderer>().material
5.particleSystem.Play()
becomes GetComponent<ParticleSystem>().Play()
6.collider2D.bounds
becomes GetComponent<Collider2D>().bounds
7.collider.bounds
becomes GetComponent<Collider>().bounds
8.audio.Play("shoot");
becomes GetComponent<AudioSource>().Play("shoot");
9.camera.depth
becomes GetComponent<Camera>().depth
I don’t have to put all of them because the example below should guide anyone do this. These are the most asked and asked components on SO.
Cache Component:
You can cache component so that you don’t have be GetComponent everytime.
Animation myAnimation;
void Start()
{
//Cache animation component
myAnimation = GetComponent<Animation>();
}
void Update()
{
if(somethingHappens)
{
//No GetComponent call required again
myAnimation.Play("Cube|moving side");
}
}