normyp
normyp

Reputation: 184

Can't use script from another script

using UnityEngine;
using System.Collections;

public class Egg : MonoBehaviour {

// Use this for initialization
void Start () {
    PlayerController playerScript = GetComponent<PlayerController> ();
}

void OnTriggerEnter2D(Collider2D coll)
{
    this.GetComponent<SpriteRenderer>().enabled = false;
    playerScript.Increment();
}
}

It won't let me use the Increment function in the OnTrigger function.

Upvotes: 0

Views: 39

Answers (2)

Chaos Monkey
Chaos Monkey

Reputation: 984

the variable playerScript is declared inside the start method, there is no variable called playerScript in the OnTriggerEnter2D method.

you should do something like this instead:

public class Egg : MonoBehaviour {

    private PlayerController playerScript;

    // Use this for initialization
    void Start () {
         playerScript = GetComponent<PlayerController> ();
    }

    void OnTriggerEnter2D(Collider2D coll)
    {
        this.GetComponent<SpriteRenderer>().enabled = false;
        playerScript.Increment();
    }
}

Upvotes: 2

Rafal Wiliński
Rafal Wiliński

Reputation: 2390

Make sure OnTriggerEnter2D is really triggered, simply add Debug.Log("Boom!"); inside OnTriggerEnter2D.

Secondly, check if playerScript is found. Add this inside OnTriggerEnter2D body

Debug.Log("Is playerScript null? "+ (playerScript == null));

Upvotes: 0

Related Questions