- Home /
 
Translating js to c#, getting NULLReferenceExeption
I am having problems with a particle in my game. I am following a tutorial that uses javascript, but I am following using C#.
 GameObject newParticles = Instantiate(hitParticles, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal)) as GameObject;
 hitParticles.transform.position = hit.point;
 hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
                 hitParticles.Emit();
 newParticles.GetComponent<ParticleAnimator>().autodestruct = true;
 
               The last line is giving me the error. Im guessing newParticles doesnt have a component "ParticleAnimator". I tried using the js script which works fine,, so I dont believe I am missing any objects in my scene, and it must be something with my code (new to C#).
Here is the working js script
 var newParticles = Instantiate(hitParticles, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
 hitParticles.transform.position = hit.point;
 hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
                     hitParticles.Emit();
 newParticles.GetComponent(ParticleAnimator).autodestruct = true;
 
              If GetComponent returns null, it means the GameObject you're searching from doesn't have that script.
Answer by perchik · Feb 27, 2014 at 08:34 PM
C# GetComponent's syntax is different, and poorly documented...
anyway, this is what you want
 newParticles.GetComponent<ParticleAnimator>().autodestruct = true;
 
              I'm actually doing that and but still getting the nullReferenceExeption. I dont know whats going on. Is there a way I can print to the console the components attached to newParticles?
Shot in the dark here,
 $$anonymous$$onoBehaviour[] scripts  = GetComponentsInChildren<$$anonymous$$onoBehaviour>();
 foreach ($$anonymous$$onoBehaviour script in scripts){
     Debug.Log(script.name);
 }
 
                 Answer by raybarrera · Feb 27, 2014 at 10:02 PM
It simply means that it did not find ParticleAnimator on the newParticles GameObject, so it's a null reference.
This may be happening if ParticleAnimator is a JS because of compile order, since the code appears to be correct and the JS version does work. Look here for more info on this: Click me
I would generally if-check this sort of thing. For example,
 ParticleAnimator particleAnimator = newParticles.GetComponent<ParticleAnimator>();
 
 if(particleAnimator != null){
     particleAnimator.autodestruct = true;
 }else{
     //Whatever.
 }
 
              Your answer
 
             Follow this Question
Related Questions
Code not working in C# 1 Answer
c# to JavaScript how? 3 Answers
Distribute terrain in zones 3 Answers
Cant get C# to talk to JavaScript 3 Answers