Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity C#, How to call a function from another script to start animation?

using UnityEngine; using System.Collections;

public class ClickToMoveScript : MonoBehaviour  
{
    public string Chopping = "Chopping";

    public void PlayWoodCuttingAnim()   
    {       
        //Play Woodcutting Animation        
        gameObject.GetComponent<Animation>().CrossFade (Chopping);  
    }     
}

Heres my other Script

using UnityEngine; 
using System.Collections;

public class WoodCuttingScript: MonoBehaviour  
{
    ClickToMoveScript ClickToMove;

    void Start()
    {
        ClickToMove.PlayWoodCuttingAnim();  
    }  
}

Unity Debugger

I have already added the animation inside the animation component.

The other thing i found out is that if i call the PlayWoodCuttingAnim() function inside ClickToMove script it works fine but in the other script it dosent work.

The error console > NullReferenceException: Object reference not set to an instance of an object.

Any help would be greatly appreciated

like image 776
OddTuna Avatar asked May 20 '26 23:05

OddTuna


2 Answers

Well, there are few common methods to do so.

Like calling method from another script you will need to get attached (to gameObject) script instance instead of simple script instance.

You can do it by,

void Start()
{
    ClickToMove = FindObjectOfType<ClickToMoveScript>();
    ClickToMove.PlayWoodCuttingAnim();  
}  
like image 69
Hamza Hasan Avatar answered May 23 '26 13:05

Hamza Hasan


Try using .GetComponent<YourScriptName>.YourFunction().

Your function will (I believe) have to be public in order to use in another script :)

like image 23
Tom Avatar answered May 23 '26 13:05

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!