Home > database >  Can't access variable from another script
Can't access variable from another script

Time:07-17

Assets\Scripts\Wood.cs(32,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

Well I'm trying to take the bool hasTorch and put it in the script Wood.cs to know if the player has a torch or not.

(I'm new so it's probably easy to fix, I just don't know :c)

Script 1 (Chest.cs):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Chest : MonoBehaviour
{
    public Sprite openChest;

    public GameObject chest1;
    public GameObject chestBox;
    public GameObject torch;

    public bool hasTorch = false;

    public GameObject darkness;
    public GameObject chatBox;

    private void OnTriggerEnter2D(Collider2D other)
    {
        chest1.GetComponent<SpriteRenderer>().sprite = openChest;
        torch.SetActive(true);
        chatBox.SetActive(true);
        darkness.SetActive(false);
        chestBox.SetActive(false);

        hasTorch = true;
    }

    public void Close()
    {
        chatBox.SetActive(false);
    }

}

Script 1 (Wood.cs):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Wood : MonoBehaviour
{

    public GameObject chestScript;
    public Chest script;

    public GameObject chatBox;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (script.hasTorch == true)
        {
            chatBox.SetActive(true);
        }

        if (script.hasTorch == true)
        {
            chatBox.SetActive(true);
        }
    }

    public void Close()
    {
        chatBox.SetActive(false);
    }

    void Start(){
        chestScript.GetComponentInChildren<Chest>().hasTorch;
    }

}

CodePudding user response:

This line does not do anything (not a valid statement, as the error suggests):

chestScript.GetComponentInChildren<Chest>().hasTorch;

you could Log it or set it to true/false like this (a valid assignment):

chestScript.GetComponentInChildren<Chest>().hasTorch = false;

CodePudding user response:

You have created a variable of type Chest but have not told Unity which Chest instance you want to access. Imagine you had a couple of GameObjects, all with this script attached, each with a different value for hasTorch. Unity wouldn't know which instance you have in mind, that is why you have to specifically assign the value.

All you have to do is to add this line into the Start() method:

script = someKindOfaGameObject.GetComponent<Chest>();

From now on you should be able to access all the public variables in the Chest script using script.variable syntax.

  • Related