- Home /
The question is answered, right answer was accepted
Accessing Instance Bool from other script
Hi, im pretty new to C# and Unity so I think my question is realy basic and simple, but i can't figure it out.
It's a litte an simple TowerDefense Game. I have some Blocks, where u are allowed to build towers. The blocks got a public bool "empty" what means you are allowed to build here and vise versa. This works perfect on all instances. As far as good.
To increase the difficult, I got now one more script. This script turns random blocks red in regular intervals. Even this works great but while they are now red, the buildplace should now set the bool from empty = false to true. I realy have no clue how to access the bool correctly.
What I tried is buildplace.empty = false; If the script happens I get this error:
NullReferenceException: Object reference not set to an instance of an object BlockThief.SeekAndDestroy () (at Assets/Scripts/BlockThief.cs:25)
This error make sense, in fact, but how can I say him he should use this instance?
Since the random block is saved in variable "block" I even tried block.empty. This wont work too. :(
Here is my Script
using UnityEngine;
using System.Collections;
public class BlockThief : MonoBehaviour {
GameObject[] blocks;
GameObject block;
Renderer rend;
Buildplace buildplace;
void Start()
{
InvokeRepeating("SeekAndDestroy",3,3);
}
void SeekAndDestroy() {
blocks = GameObject.FindGameObjectsWithTag("Buildplace");
if (blocks.Length != 0) {
block = blocks [Random.Range (0, blocks.Length)];
rend = block.GetComponent<Renderer>();
rend.material.color = Color.red;
block.empty = false; //Error (ye of course, but I dont know how use it correctly :( )
}
}
The other script is called Buildplace and the bool "empty" in there is public!
Hope anyone can help me :)
Cheers!
Answer by DoTA_KAMIKADzE · Apr 29, 2015 at 04:57 PM
block.GetComponent<Buildplace>().empty = false;
P.S. Or if you do something else with Buildplace script afterwards then go the same way that you've gone with Renderer.
Answer by brunopava · Apr 29, 2015 at 05:00 PM
void SeekAndDestroy()
{
blocks = GameObject.FindGameObjectsWithTag("Buildplace");
if (blocks.Length != 0)
{
block = blocks [Random.Range (0, blocks.Length)];
rend = block.GetComponent<Renderer>();
rend.material.color = Color.red;
// change this:
block.GetComponent<BuildPlace>().empty = false;
}
}
Follow this Question
Related Questions
Unity event calling function gets nullreferencexception on bool 0 Answers
NullReferenceException error in an array of objects 0 Answers
Why is passing this array causing some of its values to become null? 2 Answers
One variable set TRUE when another must be false. TOGGLE 3 Answers
Randomly instantiate objects from array without choosing the same item twice. 2 Answers