1

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++;
    }

}
2
  • I'm not sure what your script here is meant to do. All I see is the Hero increments lifeBall every frame and BallControl prints GameOver if it is 20... What context does this have in your game, what type of game is it and how does the hero interact with the ball? I have a feeling the answer is in Hero obj = GetComponent<Hero>(); as this tries to get a script and not another separate game object. Commented Jul 19, 2013 at 13:14
  • I just want to increase lifeBall. These codes are just prototype of my problem. If I can increase life value in BallControl, I can control Ballcontrol's animations. Example : If life == 1 then play animation1. if life == 4 then destroy object. I try to achieve this. Commented Jul 19, 2013 at 13:31

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.