The question is answered, right answer was accepted.
While instantiating getting object reference not set for no reason?
Hello. I want to instantiate a green ball and it does work but while doing that it shows me 2 same errors that say this: Object reference not set to an instance of an object. I have no idea why it would say that everything is correct and it does work like it should.
Here is the code:
using UnityEngine;
using System.Collections;
public class SimpleBulletShootAI : MonoBehaviour {
private GameObject playerobj;
public GameObject GreenPlasmaBall;
private bool allowtoshoot = false;
private float allowtoshoottimer = 3f;
private float damping = 50f;
// Use this for initialization
void Start () {
playerobj = GameObject.Find ("PlayerHuman");
}
// Update is called once per frame
void Update () {
// Shoot at player
Vector3 lookPos = playerobj.transform.position - transform.position;
lookPos.y = 0;
Quaternion rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
if (allowtoshoot == false) {
allowtoshoottimer -= Time.deltaTime;
}
if (allowtoshoottimer <= 0) {
Rigidbody gunbulletinstance;
gunbulletinstance = Instantiate(GreenPlasmaBall,transform.position,transform.rotation) as Rigidbody;
gunbulletinstance.name = "GreenPlasmaBall";
gunbulletinstance.AddForce(transform.forward * 5000);
allowtoshoottimer = 3f;
}
}
}
It says that the error is on line 36 that is: gunbulletinstance.name = "GreenPlasmaBall"; if i remove that line of code then it shows me the same 2 errors on line: gunbulletinstance.AddForce(transform.forward * 5000); . Soo how can i fix this false error? please help.
Have you tried restarting unity? I get strange errors all the time when I edit prefabs in the editor, restarting unity usually fixes them.
Answer by MountainDrew · Oct 18, 2015 at 07:05 PM
Try replacing "Rigidbody" with "GameObject" so that your code looks like this:
GameObject gunbulletinstance;
gunbulletinstance = Instantiate(GreenPlasmaBall,transform.position,transform.rotation) as GameObject;
And then you can just set the name like:
gunbulletinstance.name = "GreenPlasmaBall";
or if you want to do it via the Rigidbody component
gunbulletinstance.GetComponent<Rigidbody>().name = "GreenPlasmaBall";
And then to add the force to your gunbulletinstance
GameObject you need to get the Rigidbody component like so:
gunbulletinstance.GetComponent<Rigidbody>().AddForce(transform.forward * 5000);
It worked thank you soo much i did try GameObject first time it did not work but now when i tried it again it worked.