Matthew O
Matthew O

Reputation: 41

How do you properly address another scripts function?

I'm trying to call a function called dieAnim() in one script from another script, called Magnum.

This is in my Fire function in the Magnum script:

if (hit.collider.tag == "Alien1")
{
    Alien.dieAnim();
}

In the Alien script:

public void dieAnim()
{
    Destroy(gameObject);
}

Everytime i try to run this, it says Object reference not set to an instance of an object.

Upvotes: 1

Views: 64

Answers (3)

Sean Carey
Sean Carey

Reputation: 807

Just re-write your code to the following

if (hit.collider.tag == "Alien1")
{
    hit.collider.GetComponent<Alien>().dieAnim();
}

But if the the only thing that dieAnim is doing is destroying the alien that was hit, you don't need to call a function inside of another script for that - that's overkill.

Just do this

if (hit.collider.tag == "Alien1")
{
     Destroy(hit.gameObject);
}

Upvotes: 0

Paul Atr&#233;ides
Paul Atr&#233;ides

Reputation: 51

To run this more efficiently do

if(hit.collider.CompareTag("Alien1")){
    //either
    Destroy(hit.gameObject);
    //or if there is logic in dieAnim()
    hit.collider.GetComponent<Alien>().dieAnim();
}

The reason your code was not working was because you were calling the dieAnim() function as if it were on a static component. That means you were trying to call it on all scripts basically. You have to have a reference to that instance of the alien that you hit. The CompareTag is just a special function that allows you to compare tags of gameobjects more quickly and efficiently than a string == string comparison.

Upvotes: 1

Jlalonde
Jlalonde

Reputation: 483

In the above it looks like you're trying to call dieAnim() from the Class name of Alien

You'll want to use

hit.collider.gameobject.GetComponent<desiredcomponent>().dieAnim();

In this you're accessing the instance of the Alien class as a component.

Edit for clarity.

In the editor when you add a script you're adding a new monobehavior. These are attached to a game object as components. So when you want to access one, you have the access the components of the game object.

So in your case to get the other script you need to call get component on your the game object your colliider hit. The tag is also attached to the game object itself

Upvotes: 0

Related Questions