0

i have a game like the rool the ball game, and in my game i have a gameobject that is a gameManager, in that gameManager i instantiate the ball, what i want to do is, when my ball colides with a power add a material to a math array that is in another script, when i try accessing that script it says that Object is not instantiate, i don't know how to work on this :/.

Here is what i did

public class PowerHit : MonoBehaviour {
    MoveBall moveBall;
    Renderer rend;
    private Material yourMaterial;
    // Use this for initialization
    void Start () {
        moveBall = GameObject.FindWithTag ("Player").GetComponent<MoveBall> ();
        rend = moveBall.GetComponent<Renderer> ();
        yourMaterial = (Material)Resources.Load("Tennis",typeof(Material));
    }

    void OnCollisionEnter(Collision other)
    {
        Debug.Log (moveBall);
        if (other.gameObject.tag == "Player") {
            moveBall.mats [1] = yourMaterial;
        }
    }
}

the script that i want to acces is the MoveBall script that is atteched to my ball prefab, my ball prefa has a Player tag.

Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
  • So uh...what line is the error at? `moveBall.mats [1] = yourMaterial;`? – Serlite Jan 03 '17 at 16:35
  • Are you sure `moveBall` is not null ? What is the **exact** error message ? – Hellium Jan 03 '17 at 16:52
  • NullReferenceException: Object reference not set to an instance of an object PowerHit.Start () (at Assets/PowerHit.cs:12) –  Jan 03 '17 at 16:54
  • my 12 is the moveBall = GameObject.FindWithTag ("Player").GetComponent (); –  Jan 03 '17 at 16:55
  • If it's a null reference exception, then, take a look here : http://answers.unity3d.com/questions/47830/what-is-a-null-reference-exception-in-unity.html The problem is that you have no gameobject with the `Player` tag (maybe `player` or `PLAYER`) in your scene, OR, the gameobject with the "Player" tag in your scene does not have the `MoveBall` script attached to it. – Hellium Jan 03 '17 at 17:06
  • 1
    Another possibility is that there is more than one gameobject with a "Player" tag, and the one being returned does not have the MoveBall script. – Chairs Jan 03 '17 at 19:52

2 Answers2

0

Instantiate the ball in the Awake() function instead of Start().

Hellium
  • 7,206
  • 2
  • 19
  • 49
waqas ali
  • 194
  • 8
0
void OnCollisionEnter(Collision other)
{
    if (other.gameObject.tag == "Player") {
        other.gameObject.GetComponent<MoveBall>().mats [1] = yourMaterial;;
    }

}

You are checking that other object is player by comparing tag, if it is then you got that player and on that player there is script named "MoveBall" then you can get mats[1] reference from that script.

No need to do that stuff that you are doing on start. Just assign "yourMaterial" variable reference or load it at run time.

Nikunj Rola
  • 156
  • 5