Ali Kazemi Ali Kazemi - 3 months ago 119
C# Question

Unity 5.4 C# Animation Play/Stop

I'm trying to play/stop animations with C# codes but they didn't worked, Javascript code work (legacy mode). I hope someone know where is problem.

C#:

using UnityEngine;
using System.Collections;

public class PlayStop : MonoBehaviour

{
public GameObject Cube;


void PS()
{
GetComponent<Animation>().Play();
}
}





JS:

var Cube : GameObject;
Cube.GetComponent.<Animation>().Play();


C# Screenshot

JS Screenshot

Answer

The problem is that mentioned C# and JS code you wrote are not equivalent. In C# code you call GetComponent<Animation> to search in gameObject to which PlayStop script is attached to, while in JS script you are searching with GetComponent<Animation> in Cube gameObject you dragged from inspector.

You should try:

using UnityEngine;
using System.Collections;

public class PlayStop : MonoBehaviour

{
    public GameObject Cube;


    void PS()
    {
        Cube.GetComponent<Animation>().Play();
    }
}

To run code inside PS() on application run, rename it to Start() or move code from inside of it to new method and name it Start().

To run PS() on button click, click + in OnClick section of Button in Inspector, drag your PlayStop script to box on the left and choose the function you want to call on click from dropdown, like this:

enter image description here

Comments