Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Object reference not set to an instance of an Object C#

Discussion in 'Editor & General Support' started by micky2171, Sep 29, 2014.

  1. micky2171

    micky2171

    Joined:
    Jan 13, 2014
    Posts:
    5
    Im trying to make a multiplayer game, but the code that i am using brings up the error "Object reference not set to an instance of an Object". How can i fix this?

    My Code:

    using UnityEngine;
    using System.Collections;

    public class FP_Shooting : MonoBehaviour {

    public GameObject bullet_prefab;
    float bulletImpulse = 50f;
    float delay = 0;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void FixedUpdate () {
    if (networkView.isMine) {
    if (Input.GetButtonDown ("Fire1") && delay <= Time.time) {
    Camera cam = Camera.main;
    GameObject thebullet = (GameObject)Instantiate (bullet_prefab, cam.transform.position + cam.transform.forward, cam.transform.rotation);
    thebullet.rigidbody.AddForce (cam.transform.forward * bulletImpulse, ForceMode.Impulse);
    delay = Time.time + 0.1f;
    }
    }
    }
    }
     
  2. Graham-Dunnett

    Graham-Dunnett

    Unity Technologies

    Joined:
    Jun 2, 2009
    Posts:
    4,287
    When you get errors like this, you should also have a line number which tells you where the problem is.
     
  3. micky2171

    micky2171

    Joined:
    Jan 13, 2014
    Posts:
    5
    The error that I am getting is:

    NullReferenceException: Object reference not set to an instance of an object Shoot.FixedUpdate () (at Assets/Scripts/Shoot.cs:21)
     
  4. micky2171

    micky2171

    Joined:
    Jan 13, 2014
    Posts:
    5
    When I change the networkView.isMine to NetworkView.isMine, it stops me from running the game and says this:

    Assets/Scripts/FP_Shooting.cs(17,33): error CS0120: An object reference is required to access non-static member `UnityEngine.NetworkView.isMine'
     
  5. Graham-Dunnett

    Graham-Dunnett

    Unity Technologies

    Joined:
    Jun 2, 2009
    Posts:
    4,287
    Well, line 21 is the one that starts thebullet.rigidbody. So, I guess the question is does the prefab have a rigidbody?
     
  6. micky2171

    micky2171

    Joined:
    Jan 13, 2014
    Posts:
    5
    yes, the prefab is connected up to the bullet