Tengo problemas con este código en Unity, porqué me aparece estos errores y no se como manejarlo y necesito ayuda.
**1. NullReferenceException: Object reference not set to an instance of an object Target.Start () (at Assets/Scripts/Target.cs:21).
- NullReferenceException: Object reference not set to an instance of an object Target.OnMouseDown () (at Assets/Scripts/Target.cs:38) UnityEngine.SendMouseEvents: DoSendMouseEvents(Int32)**
Este es el código de Target:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Target: MonoBehaviour
{
private Rigidbody targetRb;
private GameManager gameManager;
private float minSpeed = 12;
private float maxSpeed = 16;
private float maxTorque = 10;
private float xRange = 4;
private float ySpawnPos = -6;
public int pointValue;
// Start is called before the first frame update
void Start()
{
targetRb = GetComponent<Rigidbody>();
gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
targetRb.AddForce(RandomForce(), ForceMode.Impulse);
targetRb.AddTorque(RandomTorque(), RandomTorque(), RandomTorque(), ForceMode.Impulse);
transform.position = RandomSpawnPos();
}
// Update is called once per frame
void Update()
{
}
private void OnMouseDown()
{
Destroy(gameObject);
gameManager.UpdateScore(pointValue);
}
private void OnTriggerEnter(Collider other)
{
Destroy(gameObject);
}
Vector3 RandomForce()
{
return Vector3.up * Random.Range(minSpeed, maxSpeed);
}
float RandomTorque()
{
return Random.Range(-maxTorque, maxTorque);
}
Vector3 RandomSpawnPos()
{
return new Vector3(Random.Range(-xRange, xRange), ySpawnPos);
}
}
Este otro codigo es de Game Manager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class GameManager: MonoBehaviour
{
public List<GameObject> targets;
public TextMeshProUGUI scoreText;
private int score;
private float spawnRate = 1.0f;
// Start is called before the first frame update
void Start()
{
StartCoroutine(SpawnTarget());
score = 0;
UpdateScore(0);
}
// Update is called once per frame
void Update()
{
}
IEnumerator SpawnTarget()
{
while (true)
{
yield return new WaitForSeconds(spawnRate);
int index = Random.Range(0, targets.Count);
Instantiate(targets[index]);
UpdateScore(5);
}
}
public void UpdateScore(int scoreToAdd)
{
score += scoreToAdd;
scoreText.text = "Score: " + score;
}
}
El error aparece en la linea 21:
gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
Esté error aparece en la linea 38:
gameManager.UpdateScore(pointValue);
Si ustedes me pueden brindar ayuda se los voy agradecer. Muchas gracias.
new
en la linea de GameObject y GameManager tampoco esta instanciado en ningun lugar connew