исключение нулевой ссылки при доступе к переменной из префаба - PullRequest
0 голосов
/ 02 мая 2019

Я получаю ошибку исключения нулевой ссылки при попытке изменить логическое значение на правое (или левое в этом отношении).Мой префаб должен появиться в FirepointL.

Мой сценарий распознает предпочтение, так как он не возвращает значение Null для поиска префаба (проверено это).

Я убедился, что мой логический параметр былустановил Public, и я сбросил все GameObjects в их назначенные места в Инспекторе.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public GameObject bullet;

    private Rigidbody2D myRigidbody;
    private float speed = 15;
    private bool facingRight;
    private bool ground = false;
    private float jump = 23;
    // Start is called before the first frame update
    void Start()
    {
        facingRight = true;
        myRigidbody = GetComponent<Rigidbody2D>();

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float horizontal = Input.GetAxis("Horizontal");

        bullet = GameObject.FindGameObjectWithTag("Button");


        Movement(horizontal);
        Flip(horizontal);
        if (Input.GetKey("w"))
        {
            if (ground)
            {
                GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
            }
        }
       // this is the part that returns the error
        if (facingRight == true)
        {
            bullet.GetComponent<weapon>().right = true;
        }
        if (facingRight == false)
        {
            bullet.GetComponent<weapon>().right = false;
        }

    }

    void OnTriggerEnter2D()
    {
        ground = true;
    }

    void OnTriggerExit2D()
    {
        ground = false;
    }

    private void Movement(float horizontal)
    {

        myRigidbody.velocity = new Vector2(horizontal * speed,myRigidbody.velocity.y);
    }

    private void Flip(float horizontal)
    {
        if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
        {
            facingRight = !facingRight;

            Vector3 theScale = transform.localScale;

            theScale.x *= -1;

            transform.localScale = theScale;
        }


    }


}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class weapon : MonoBehaviour
{
    // Start is called before the first frame update
    public bool right;
    public Transform firepointR;
    public Transform firepointL;
    public GameObject bulletPrefab;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            Debug.Log("It's the space key");
            Shoot();
        }

    }

    void Shoot()
    {
        if (right == true)
        {
            Instantiate(bulletPrefab, firepointR.position, firepointR.rotation);
        }
        if(right == false)
        {
            Instantiate(bulletPrefab, firepointL.position, firepointL.rotation);
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class bullet : MonoBehaviour
{
    public float speed = 20;

    public Rigidbody2D rb;
    // Start is called before the first frame update
    void Start()
    {
        rb.velocity = transform.right * speed;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Ответы [ 2 ]

0 голосов
/ 02 мая 2019

Я думаю, что есть проблема с соглашениями об именах. Вы пытаетесь найти пулю с именем «Button», но когда вы создаете экземпляр игрового объекта, он называет его чем-то вроде Button (клон).

Одно решение, которое приходит мне в голову:

1-й шаг:

Создание публичной статической переменной в скрипте PlayerMovement.

    public static PlayerMovement Instance;


private void Awake()
{
    Instance = this;
}

Установите его значение внутри функции пробуждения, чтобы вы могли вызывать его из любого места.

2-й шаг:

Я изменил функцию съемки.

void Shoot()
{
    GameObject _firePosition = right == true ? firepointR : firepointL;
    PlayerMovement.Instance.bullet = Instantiate(bulletPrefab, _firePosition.position, _firePosition.rotation); // we are setting the reference on runtime whenever we spawn a new bullet.
 }

3-й шаг:

Удалите эту строку из сценария PlayerMovement, так как она сейчас не нужна.

        bullet = GameObject.FindGameObjectWithTag("Button");

PS: Код не будет работать, если вы не выполните шаг 3. Дайте мне знать, если это поможет. :)

0 голосов
/ 02 мая 2019

Не уверен, что это точная проблема, но есть проблема в классе PlayerMovement.Когда вы извлекаете bullet, вы предполагаете, что объект с тегом Button присутствует.

На мой взгляд, вы должны проверить его с помощью

// this is the part that returns the error
if (bullet && facingRight == true)
{
    bullet.GetComponent<weapon>().right = true;
}
if (bullet && facingRight == false)
{
    bullet.GetComponent<weapon>().right = false;
}
...