Reputation: 425
I have two scripts. The first script BallControl is attached on a GameObject. The Second script Hero is attached on other GameObject. When I try to passing value Hero to BallControl, I receive an error message : "NullReferenceException: Object reference not set to an instance of an object" How can I solve this problem or how can I pass value script attached on an object to other script attached on an other object? Thanks for your time.
using UnityEngine;
using System.Collections;
public class BallControl : MonoBehaviour {
public int life = 0;
public GameObject hero;
void Update () {
Hero obj = GetComponent<Hero>();
life = obj.lifeBall;
if(life==20){
print("GameOver");
}
}
}
//
using UnityEngine;
using System.Collections;
public class Hero : MonoBehaviour {
public int lifeBall = 0;
public GameObject ball;
void Update () {
lifeBall++;
}
}
Upvotes: 1
Views: 6016
Reputation: 13146
As you said that Hero
is attached to another game object, you need to get the reference from this other object. Assuming GameObject hero
is the one the containing Hero
component, than you need:
Hero obj = hero.GetComponent<Hero>();
Assure that you have dragged the game object of hero to the member hero
of the ball controlling game object.
Anyway life would be easier if you declare public Hero hero
instead of public GameObject hero
and drag the game object of hero to it. Than you don't need to call GetComponent
but can use it directly.
Upvotes: 3