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

Can't figure out this error.

Discussion in '2D' started by LaliKinux, May 17, 2016.

  1. LaliKinux

    LaliKinux

    Joined:
    Apr 26, 2016
    Posts:
    38
    So it's probably something stupid but I can't seem to figure it out..

    I'm making a system where when you touch the "coin", it gives +1 to the score and goes away, but I'm running into some issues. Here's the main code with the text on it. (I know, it's a lot more than just player movement on that script, but I'm just now learning how to make scripts talk to eachother..)

    Here's what's on the player:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.  
    8.     public float speed = 5.0f;
    9.     public float jumpHeight = 20.0f;
    10.     public float minX;
    11.     public float maxX;
    12.     public Text scoreText;
    13.     private int score;
    14.     private bool colorSwitch = true;
    15.     private bool isGrounded = false;
    16.     private Rigidbody2D myRigid;
    17.  
    18.  
    19.     void Start ()
    20.     {
    21.         myRigid = this.GetComponent<Rigidbody2D> ();
    22.         score = 0;
    23.         scoreText.text = "Coins: " + score.ToString();
    24.     }
    25.    
    26.     void Update ()
    27.     {
    28.         if(Input.GetKeyDown (KeyCode.S))
    29.         {
    30.             colorSwitch = !colorSwitch;
    31.         }
    32.  
    33.         if(colorSwitch)
    34.         {
    35.             this.GetComponent<SpriteRenderer> ().color = Color.black;
    36.         }
    37.         else
    38.         {
    39.             this.GetComponent<SpriteRenderer> ().color = Color.white;
    40.         }
    41.  
    42.     }
    43.     void FixedUpdate ()
    44.     {
    45.  
    46.  
    47.         if (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.W) || Input.GetKeyDown (KeyCode.UpArrow))
    48.         {
    49.             if (isGrounded)
    50.             {
    51.                 myRigid.velocity = new Vector2 (myRigid.velocity.x, jumpHeight);
    52.                 Debug.Log (" I am jumping ");
    53.             }
    54.         }
    55.  
    56.         if (Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.LeftArrow))
    57.             {
    58.                    
    59.                 myRigid.velocity = new Vector2 (-speed, myRigid.velocity.y);
    60.                 Debug.Log (" Moving RIGHT ");
    61.  
    62.             }
    63.  
    64.         if (Input.GetKey (KeyCode.D) || Input.GetKey (KeyCode.RightArrow))
    65.             {
    66.  
    67.                 myRigid.velocity = new Vector2 (speed, myRigid.velocity.y);
    68.                 Debug.Log (" Moving LEFT ");
    69.  
    70.             }
    71.  
    72.         if (myRigid.position.x <= minX)
    73.         {
    74.             myRigid.position = new Vector2 (minX, myRigid.position.y);
    75.         }
    76.         else if (myRigid.position.x >= maxX)
    77.         {
    78.             myRigid.position = new Vector2 (maxX, myRigid.position.y);
    79.         }
    80.            
    81.     }
    82.  
    83.     void OnTriggerEnter2D ()
    84.     {
    85.         isGrounded = true;
    86.         Debug.Log (" Detecting ground ");
    87.    
    88.     }
    89.  
    90.     void OnTriggerExit2D ()
    91.     {
    92.         isGrounded = false;
    93.         Debug.Log (" Not touching ground ");
    94.  
    95.     }
    96.  
    97.     void OnCollisionEnter2D ()
    98.     {
    99.         if (myRigid.CompareTag ("Coin"))
    100.         {
    101.             setScore ();
    102.         }
    103.     }
    104.  
    105.     void setScore ()
    106.     {
    107.         if (CoinDestroy.isCollected == false)
    108.         {
    109.             score = score + 1;
    110.             scoreText.text = "Coins: " + score.ToString ();
    111.         }
    112.     }
    113. }
    114.  
    Here's what's on the coins:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class CoinDestroy : MonoBehaviour
    4. {
    5.     static public bool isCollected = false;
    6.  
    7.  
    8.     static void OnCollisionEnter2D(Collision2D col)
    9.     {
    10.         if (col.gameObject.tag == "Player")
    11.         {
    12.             col.gameObject.SetActive (false);
    13.             isCollected = true;
    14.         }
    15.            
    16.     }
    17. }
    18.  
    Error message:
    As you can see, the only way I've figured out how to do this is to set it invisible instead of destroying it.

    Any tips? Is there an easier way to approach this? This seems like a lot for just a coin I can pick up. I've watched the tutorials and looked through their code and can't figure out why mine isn't working.
    An explanation would be awesome as well.. Thanks guys.
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Well it seems since you've edited the code, that error message's line number doesn't match up. It says you have a null object in your Start() method in your PlayerMovement script.

    It's probably scoreText. Are you assigning that in the inspector properly?

    Null reference means that you tried to access a variable that was holding nothing. So maybe "scoreText.text =" threw a null reference because "scoreText" didn't have a reference, and you tried to access the "text" property of nothing.

    When in doubt, null check:
    Code (CSharp):
    1. if(scoreText != null){
    2.     scoreText.text = "score";
    3. }
    Also just some tips, get all your components in Start() or Awake(). You almost never want to use GetComponent inside Update(). Unless things are gaining and losing components during gameplay, you only need to use "GetComponent" once to get it, then you can continue to use it throughout your class. So create variables to store your component references.

    You don't need to do "this.GetComponent", without "this" will work just fine.

    You definitely DO NOT want to make "isCollected" a static variable of CoinDestroy. That means that every single Coin will share that one variable. If one coin sets that, it will be set for all of them.

    Try something like this:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class CoinDestroy : MonoBehaviour {
    4.     public int value = 1;
    5.  
    6.     private void OnCollisionEnter2D(Collision2D col) {
    7.  
    8.         // try to get the PlayerMovement component of whatever the coin collided with
    9.         PlayerMovement player = col.gameObject.GetComponent<PlayerMovement>();
    10.  
    11.         // if the 'player' variable isn't null, that means we hit something with a PlayerMovement component
    12.         if(player != null) {
    13.  
    14.             // add this coin's value to the player's score
    15.             player.addScore(value);
    16.  
    17.             // destroy this coin gameobject
    18.             Destroy(gameObject);
    19.         }
    20.     }
    21. }
    Then in your PlayerMovement script, you should get rid of the collision code (generally collision should be handled just on one of the two colliding objects), and have a function called "addScore" like this:

    Code (CSharp):
    1. public void addScore(int points) {
    2.     score += points;
    3.     updateScoreText();
    4. }
    5.  
    6. private void updateScoreText(){
    7.     scoreText.text = "Coins: " + score.ToString();
    8. }
    You can also have your existing "setScore" to set the value directly, but I think addScore will be useful to you. I also added a function to update your score string, which you can call any time you change the score.
     
    Last edited: May 17, 2016
  3. LaliKinux

    LaliKinux

    Joined:
    Apr 26, 2016
    Posts:
    38
    I'm getting all types of errors when trying to change things up like you said.
    Updated code:


    PlayerMovement:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.  
    8.     public float speed = 5.0f;
    9.     public float jumpHeight = 20.0f;
    10.     public float minX;
    11.     public float maxX;
    12.     public Text scoreText;
    13.     public int addScore;
    14.     private bool colorSwitch = true;
    15.     private bool isGrounded = false;
    16.     private Rigidbody2D myRigid;
    17.  
    18.  
    19.     void Start ()
    20.     {
    21.        
    22.     }
    23.    
    24.     void Update ()
    25.     {
    26.         if(Input.GetKeyDown (KeyCode.S))
    27.         {
    28.             colorSwitch = !colorSwitch;
    29.         }
    30.  
    31.         if(colorSwitch)
    32.         {
    33.             this.GetComponent<SpriteRenderer> ().color = Color.black;
    34.         }
    35.         else
    36.         {
    37.             this.GetComponent<SpriteRenderer> ().color = Color.white;
    38.         }
    39.  
    40.     }
    41.     void FixedUpdate ()
    42.     {
    43.  
    44.  
    45.         if (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.W) || Input.GetKeyDown (KeyCode.UpArrow))
    46.         {
    47.             if (isGrounded)
    48.             {
    49.                 myRigid.velocity = new Vector2 (myRigid.velocity.x, jumpHeight);
    50.                 Debug.Log (" I am jumping ");
    51.             }
    52.         }
    53.  
    54.         if (Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.LeftArrow))
    55.             {
    56.                    
    57.                 myRigid.velocity = new Vector2 (-speed, myRigid.velocity.y);
    58.                 Debug.Log (" Moving RIGHT ");
    59.  
    60.             }
    61.  
    62.         if (Input.GetKey (KeyCode.D) || Input.GetKey (KeyCode.RightArrow))
    63.             {
    64.  
    65.                 myRigid.velocity = new Vector2 (speed, myRigid.velocity.y);
    66.                 Debug.Log (" Moving LEFT ");
    67.  
    68.             }
    69.  
    70.         if (myRigid.position.x <= minX)
    71.         {
    72.             myRigid.position = new Vector2 (minX, myRigid.position.y);
    73.         }
    74.         else if (myRigid.position.x >= maxX)
    75.         {
    76.             myRigid.position = new Vector2 (maxX, myRigid.position.y);
    77.         }
    78.            
    79.     }
    80.  
    81.     void OnTriggerEnter2D ()
    82.     {
    83.         isGrounded = true;
    84.         Debug.Log (" Detecting ground ");
    85.    
    86.     }
    87.  
    88.     void OnTriggerExit2D ()
    89.     {
    90.         isGrounded = false;
    91.         Debug.Log (" Not touching ground ");
    92.  
    93.     }
    94.  
    95.     void OnCollisionEnter2D ()
    96.     {
    97.         if (myRigid.CompareTag ("Coin"))
    98.         {
    99.             updateScoreText ();
    100.         }
    101.     }
    102.        
    103.  
    104.     public void addScore(int points) {
    105.         addScore += points;
    106.         updateScoreText();
    107.     }
    108.  
    109.     private void updateScoreText(){
    110.         scoreText.text = "Coins: " + addScore.toString();
    111.     }
    112. }
    113.  
    Error:
     
  4. Aedous

    Aedous

    Joined:
    Jun 20, 2009
    Posts:
    244
    You've got a variable name:
    public int addScrore on line 13

    and a Method/Function name
    public void addScore(int points) on line 104

    It's best to rename your functions just like you did with the previous functions, with upper case letters. It's let you know the difference between a function name and also a variable.
    Code (CSharp):
    1.  
    2. //Variable name to keep current score
    3. public int addScore = 0;
    4.  
    5. //Function name to add points to addScore
    6. public void AddScore(int points)
    7. {
    8.   //Add score code in here
    9. }
    Have a look through this video to better understand how things work in C#, it's not that long either :D.
    https://unity3d.com/learn/tutorials...ning-archive/coding-for-the-absolute-beginner
     
    LiterallyJeff likes this.
  5. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    You never gave your variable "myRigid" a value. You need to put this in your start function:
    Code (CSharp):
    1. myRigid = GetComponent<Rigidbody2D>();
    Then anywhere you use "GetComponent<Rigidbody2D>()" you can replace with "myRigid"
     
    Last edited: May 20, 2016