Search Unity

Errors

Discussion in '2D' started by Manillan01, Aug 22, 2016.

  1. Manillan01

    Manillan01

    Joined:
    Feb 15, 2016
    Posts:
    5
    I have been making a game recently and have been having trouble with accessing other scripts (I'm very new to C#). I am getting Errors CS0117 and CS0120. I am also getting "NullReferenceException: Object reference not set to an instance of an object".

    Here are the two scripts, and if anyone could provide some info on what I am doing wrong that would be great.

    using UnityEngine;
    using System.Collections;

    public class Death : MonoBehaviour
    {
    public void Reset1() {
    transform.position = new Vector3(-11.38f,1.67f,0f);
    print(transform.position.x);

    DeathSecond deathSecond = GameObject.Player2.GetComponent<DeathSecond>();
    DeathSecond.Reset2();
    }
    void OnCollisionEnter2D (Collision2D col)
    {
    if (col.gameObject.tag == "Shell") {
    Reset1 ();
    }
    }

    }



    using UnityEngine;
    using System.Collections;

    public class DeathSecond : MonoBehaviour
    {
    public void Reset2() {
    transform.position = new Vector3(-53.1f,22f,0f);
    print(transform.position.x);
    }
    void OnCollisionEnter2D (Collision2D col)
    {
    if (col.gameObject.tag == "Shell") {
    Reset2 ();
    }
    }
    }

    Thanks!
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Please use Code Tags when pasting code snippets into the forums.

    Also, please provide the full error message including file names and line numbers aka "stack trace".
     
  3. juicyz

    juicyz

    Joined:
    Jan 14, 2016
    Posts:
    85
    As Jeff said, format your code to make it more readable and full errors because they will show lines and such.

    From reading the code, it appears:
    DeathSecond deathSecond = GameObject.Player2.GetComponent<DeathSecond>();
    AND
    DeathSecond.Reset2();
    would be the problem.

    DeathSecond.Reset2() should be deathSecond.Reset2(); ***Notice lowercase d***

    Are both scripts attached to a gameobject? There appears to be no reference to GameObject.Player2 anywhere I can see. I don't know all that much about Unity Syntax still but I don't think you can write it like that. GameObject.findObjectWithTags("Player2").GetComponent<DeathSecond>(); OR GameObject.Find("Player2").... or something to that assort. Or make a Player2 variable and use the GUI to drag Player2 in then reference the script directly with the GetComponent method.
     
    Last edited: Aug 25, 2016
  4. Manillan01

    Manillan01

    Joined:
    Feb 15, 2016
    Posts:
    5
    Sorry for the badly formatted code.

    juicyz - your solution worked! Thanks for the help.