NullReferenceExeption mais variable initialisée
Bonjour tout le monde, j'obtiens l'erreur suivante, NullReferenceException: Object reference not set to an instance of an object. Je sais déjà que le code incriminé est le "&& gameObject.name != Parent.name" dans la ligne du if(col.game...), cette erreur devrait apparaître si je n'avais pas initialisé la variable Parent, or celle-ci l'est quelques lignes plus haut. Cela fait un bon bout de temps que je m'arrache les cheveux à trouver une solution, pouvez vous m'aider ?
NB: la définition "GetComponent().parent = null;" est ici pour empêcher le projectile de suivre les mouvements du parent, en d'autres termes, je me sers juste du parent de l'objet pour en créer une référence.
GameObject Parent;
void Start()
{
Parent = GetComponent<Transform>().parent.gameObject;
//On déclare le joueur "parent" du projectile
GetComponent<Transform>().parent = null;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Player" && gameObject.name != Parent.name)
{
GameObject[] Players = GameObject.FindGameObjectsWithTag("Player");
Debug.Log("Appel de la fonction d'inversion de position: " + Players[1].name + "" + Players[0].name);
Library.InversePos(Players[1], Players[0]);
Destroy(gameObject);
}
}
Google Translation:
Hello everyone, I get the following error, NullReferenceException: Object reference not set to an instance of an object. I already know that the offending code is "gameObject.name &&! = Parent.name" in line if (col.game ...), this error would appear if I had not initiated the Parent variable, gold it is the few lines. It's been a while since I tear my hair to find a solution, can you help me?
NB: the definition "GetComponent () parent = null;." is here to prevent the projectile to follow the movements of the parent, in other words, I use just the parent of the object to create a reference.
Answer by SharpCoder · Apr 11, 2016 at 08:15 PM
I am not sure, but I think that you should try using Destroy instead of nulling...
http://answers.unity3d.com/questions/984752/destroy-vs-nulling-an-object-created-in-script-c.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612074632im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
MonoBehaviour Update called twice, fields being set to null 0 Answers
Unity Bug? null reference exception, Only its not null... 0 Answers
help with a camera bug 0 Answers
[Forum bugged, can't delete] 0 Answers
Rigid body can't find the instance 2 Answers