Home>

Please write your question in detail here.
I'm trying to set the collision between arrow and player by hand in Unity, but I get an error.
From the player side, I thought there might be a problem finding arrowPrefab in Find, and when I set Debub.Log, it was still null. But I don't know why it is null.
Even if you have a player at startup, you may think that it will take time to generate an arrow for a moment, and in the lower part, I'm trying to put a countermeasure when it becomes null. .
For the time being, arrow is flying well, so I think it's a problem with this program. I would be glad if you could give me some hints ^^
Thank you.

Error message
NullReferenceException: Object reference not set to an instance of an object
playerController.Update () (at Assets/playerController.cs: 29)
Applicable source code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController: MonoBehaviour {
    Vector2 arrowPos;
    Vector2 playerPos;
    Vector2 dir;
    GameObject arrow;

    // Use this for initialization
    void Start () {
    }
    // Update is called once per frame
    void Update () {
       this.arrow = GameObject.Find ("arrowPrefab (Clone)");
        Debug.Log (arrow);
        if (Input.GetKeyDown (KeyCode.LeftArrow))
        {
            transform.Translate (-1, 0, 0);
        } else if (Input.GetKeyDown (KeyCode.RightArrow)) {
            transform.Translate (1, 0, 0);
        }
        playerPos = transform.position;
        arrowPos = arrow.transform.position;
        if (arrowPos == null) {arrowPos = new Vector2 (0, 0);} else
        {
            dir = (playerPos-arrowPos);
            Debug.Log (arrowPos);
        }

      // if (dir.magnitude<1.5) {}

    }
}
Tried Supplemental information (FW/tool version etc.)

Please provide more detailed information here.

Unity 2018
VisualStudio2017

  • Answer # 1

    It ’s not "arrowPrefab (Clone)" but "arrowPrefab (Clone)".
    There is a space between them.

    In my opinion, GameObject.Find () is troublesome to specify names like this, and it can not be distinguished when there is an object with the same name, so I think that it is good to use other methods .
    Also, since I am using Unity, I think that it is better to use Collider for collision detection instead of handwriting.
    Because it takes time and effort to become more complicated.