- Home /
Why I can't change the Boolean value in another class
After the prefab it instantiated, it cannot change the value of the Game Controller Class. Why?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MazeScript : MonoBehaviour
{
public GameController gameController;
public float moveSpeed = 5.0f;
public Transform destroyPoint;
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.back * moveSpeed * Time.deltaTime);
if (transform.position.z <= destroyPoint.position.z)
{
Debug.Log("Can Destroy!");
this.gameController.canRemoveFromList = true;
Destroy(gameObject);
}
}
}
I don't know if I got your scenario right but anyway.. you cannot reference scene components from prefab directly. You need to set them after instantiating it (in Start() or Awake()). If your GameController uses singleton pattern then just use its static reference variable to access its public members. If it doesn't have one then you need to find the component it in the scene. There are many ways to get the right component reference.. here is one: In Start() or Awake() use GameObject.Find
(https://docs.unity3d.com/ScriptReference/GameObject.Find.html) to find the correct [gameobject] and then use gameController = [gameobject].GetCompoment<GameController>()
to get and set the components reference. Via that reference you can access its members.. Hope this helps
Answer by swanne · Oct 11, 2020 at 06:59 PM
Hi,
I think the problem comes from the instantiated object not knowing where the GameController is.
You need to add a Start function on the instantiated object and tell it which object has the GameController script on it as a component. For example
void Start()
{
gameController = GameObject.Find("GameController").GetComponent<GameController>();
}
Your answer
Follow this Question
Related Questions
How to change a Bool for only a single prefab GameObject? 1 Answer
How to start animation after dialogue ends a.k.a currentLine == 3 1 Answer
Need help accessing booleans from other script. 2 Answers
Returning bool from another script (Cannot implicitly convert type 'void' to 'bool') 2 Answers
How to change bool values from one controlling script to a receiver? 1 Answer