- Home /
Variable Assigned Error along with "Name "" Not Assigned in Current Context
Hi, I'm using GetComponent to grab a bool from this script:
using UnityEngine;
using System.Collections;
public class GameObjectDisable : MonoBehaviour {
public Material PlaceRed;
public Material PlaceGreen;
public bool CanPlace;
void Start (){
GameObject GhostObject = GameObject.Find("planetstationtransparent(Clone)");
}
void OnCollisionEnter (Collision col) { //if in contact, change to red and make non placeable
if(col.gameObject.name == "planetstationtransparent(Clone)")
{
GhostObject.GetComponent<Renderer>().material = PlaceRed;
bool CanPlace = false;
}
}
void OnCollisionExit(Collision col) { //if no longer in contact, change back to green and placeable
if(col.gameObject.name == "planetstationtransparent(Clone)")
{
GhostObject.GetComponent<Renderer>().material = PlaceGreen;
bool CanPlace = true;
}
}
}
And use it to see if it can pass the if statement in this script.
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
public class Builder : MonoBehaviour {
public GameObject BuildingFinal;
public GameObject GhostObject;
public Builder BuilderToggle;
// Use this for initialization
void Start () {
GameObject Water = GameObject.FindWithTag("Water");
//grabs itself so it can be disabled in the future
BuilderToggle = GetComponent<Builder>();
//makes translucent object with red and half opacity TODO: GET THIS TO WORK
GhostObject = (GameObject)Instantiate(Resources.Load("planetstationtransparent"));
}
// Update is called once per frame
void Update () {
//re-enables the object if previously disabled
GhostObject.SetActive(true);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit)){
Vector3 Placement = hit.point;
GhostObject.transform.position = Placement;
GhostObject.transform.up = hit.normal;
//transform up is for rotation
// previous code is for the raycasting of planet mesh
if (Input.GetMouseButtonDown(0) && Water.GetComponent<GameObjectDisable>().CanPlace == true) {
BuildingFinal = (GameObject)Instantiate(Resources.Load("planetstation"));
BuildingFinal.transform.position = Placement;
BuilderToggle.enabled = false;
}
if (Input.GetMouseButtonDown(1)){
GhostObject.SetActive(false);
BuilderToggle.enabled = false;
}
}
}
}
I posted the entire code because I'm not sure where the error lies. The first script goes on the Water GameObject, declaring that if it is in contact, make it not placeable, and Red
Comment
I don't know what you are asking but try not declaring (creating) a duplicate variable called CanPlace
inside the OnCollisionEnter and Exit.
Change
bool CanPlace = false;
to
CanPlace = false;
With the bool
word you are creating a new variable that only exists inside the function and disappears when you exit the function call.
Your answer
![](https://koobas.hobune.stream/wayback/20220613192552im_/https://answers.unity.com/themes/thub/images/avi.jpg)