简体   繁体   中英

Unity c# Code working in one script but not in other?

Hey guys so I have this really strange problem, so basically what happens is the player runs into the box (OnTriggerEnter function) and a weapon will show on the character and the box will spawn to another location. Except I tried to make a separate script because the script that it works on is for spawning boxes. I didn't want it in the same script because not as neat.

So this is my code for the script where it doesn't work:

public class ChangeGun : MonoBehaviour {

    public Sprite gunSprite;

    private string[] weapons = { "Pistol", "Shotgun", "Ak47", "Bazooka" };

    public GameObject currentGun;

    public void AddGunToPlayer()
    {
        //int randomNumber = Random.Range(0, 4);
        currentGun.GetComponent<SpriteRenderer>().sprite = gunSprite;

    }

}

And this is the script where it works (keep in mind I used the EXACT same code, ignore all the code in this script except the for the 2 variables and the OnTriggerEnter Function.)

public class BoxGenerator : MonoBehaviour
{
    public GameObject currentGun;

    public Sprite gunSprite;

    public Vector3[] boxPositions;

    public GameObject box;

    public GameObject startingBox;

    int randomNumber;

    // Use this for initialization
    void Start()
    {
        //random number between 0-10 thats vector size
        randomNumber = Random.Range(0, 10);

        //instantiate the starting box
        startingBox = Instantiate(box);

        //set starting box to new location
        startingBox.transform.position = boxPositions[randomNumber];

        //set tag to box
        startingBox.tag = "box";

    }

    void Update()
    {
        randomNumber = Random.Range(0, 10);
    }

    void OnTriggerEnter(Collider col)
    {
        if (col.GetComponent<Collider>().tag == "box")
        {
            startingBox.transform.position = boxPositions[randomNumber];

            currentGun.GetComponent<SpriteRenderer>().sprite = gunSprite;

        }
    }
}

Keep in mind when I tried to use the old script under this line "currentGun.GetComponent().sprite = gunSprite;"

I pasted this code and got the null reference exception.

      ChangeGun cg = new ChangeGun();
        cg.AddGunToPlayer();

ChangeGun is null since you didn't set it. You said you set it in the inspector, but in your question you created in in the code so it will have the default values.

ChangeGun cg = new ChangeGun(); // cg.currentGun is null
cg.AddGunToPlayer(); // Trying to access cg.currentGun

I suppose you have set in in the inspector, so instead of creating new ChangeGun, you need to get the component you created in Inspector:

ChangeGun cg = GetComponent<ChangeGun>();
cg.AddGunToPlayer();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM