Search Unity

Object reference not set to an instance of an object

Discussion in 'Scripting' started by larswik, Feb 10, 2019.

  1. larswik

    larswik

    Joined:
    Dec 20, 2012
    Posts:
    312
    Disregard. After all these hours the code is just fine. but I never added the script to the cannon ball prefab. How stupid, sorry.


    So I have had this issue many times regarding Object refference not found, I know what it means and almost always how to fix it. But this time I have issues I can't solve?

    I have a turn based game where 2 castles are shooting at each other. They both share a CastleScript and when the right or left side fires, the script looks at the MainCamera X position to find find out which castle is shooting, right side or left side.

    So the code
    Code (CSharp):
    1. public void fireCannon(){
    2.         bool isRightSide = (GameObject.FindGameObjectWithTag("MainCamera").transform.position.x > 0)? true : false;
    3.         GameObject cBall = null;
    4.         if (castleName == "Castle_Right" && isRightSide){
    5.             print("Shot Right: " + savedCannonAngle + " Force: " + savedCannonShotForce);
    6.             cBall = Instantiate(ammoInventory[0], ballSpawnPoint.transform.position, ballSpawnPoint.transform.rotation) as GameObject;
    7.         }
    8.  
    9.         if (gameObject.name == "Castle_Left" && isRightSide == false){
    10.             print("Shot Left: " + savedCannonAngle + " Force: " + savedCannonShotForce);
    11.             cBall = Instantiate(ammoInventory[0], ballSpawnPoint.transform.position, ballSpawnPoint.transform.rotation) as GameObject;
    12.          
    13.         }
    14.         if(cBall){
    15.             cBall.GetComponent<CannonBallScript>().setCannonBallAngleAndForce(setForce:savedCannonShotForce);  
    16.         }    
    The problem is happening in the last line of code, IF cBall.GetComponent..., that is the null reference
    As I set break points I can see the GameObject Instantiate and it does appear on one side of the other depending on who's shooting. If the object didn't exist, then the that last if statement should be ignored, but it is executing and I am getting an error when it does, I don't get it?
     
    Last edited: Feb 10, 2019