Accessing a variable from another script C# UNITY [duplicate] - c#

This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 6 years ago.
I have two script
simplecloudhander.cs
cloudtarget.cs
simplecloudhander.cs
public string mTargetMetadata = "";
public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
{
GameObject newImageTarget = Instantiate(ImageTargetTemplate.gameObject) as GameObject;
GameObject augmentation = null;
string model_name = targetSearchResult.MetaData;
if( augmentation != null )
augmentation.transform.parent = newImageTarget.transform;
ImageTargetAbstractBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, newImageTarget);
Debug.Log("Metadata value is " + model_name );
mTargetMetadata = model_name;
}
i want to access mTargetMetadata value in another cloudtarget.cs script
here cloudtarget.cs script
void OnGUI() {
SimpleCloudHandler sc = new SimpleCloudHandler ();
GUI.Label (new Rect(100,300,300,50), "Metadata: " + sc.mTargetMetadata);
}
but i can't get mTargetMetadata value in another script

You have to add a reference to that script in the cloudtarget script. Just add a public variable of type SimpleCloudHandler to the class cloudtarget, not on the OnGUI method, later drag and drop the GameObject with the SimpleCloudHandler atached to the script cloudtarget in the inspector.
Example:
Drag and drop the MainCamera with the SimpleCloudHandler script attached => to the public SimpleCloudHandler variable of the cloudtarget script through the inspector.
There are multiple ways to make a reference in Unity, I recommend you to look to the documentation that Unity offer

if your scripts are attached to the same object then you can use GetComponentlike this,
gameObject.GetComponent<simplecloudhander>().mTargetMetadata
if they are not attached to the same gameObjectthe you can use GameObject.Find first to find the gameObject that the script is attached to, you should use the name of the gameObject to find it, then use the GetComponent to get the componentthat you want
GameObject.Find("nameOftheGameObject").GetComponent<simplecloudhander>().mTargetMetadata
also there is no need for new keyword, if you just want to access it,
simplecloudhander sch;
void Start()
{
sch = GameObject.Find("nameOftheGameObject").GetComponent<simplecloudhander>();
}
void OnGUI() {
GUI.Label (new Rect(100,300,300,50), "Metadata: " + sch .mTargetMetadata);
}

Related

How to read a variable from another script in Unity [duplicate]

This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 25 days ago.
I want that when the player have low health, a red screen (already did a loop animation for it) with an animation plays (it plays automatically that's why im just activating the gameObject),I tried to do it with saving the value in a text file and read it from the other script, but is not optimized and it doesn't work, what it looks like :
public void CreateText()
{
string path = Application.dataPath + "/Datas/data";
if (!File.Exists(path))
{
File.WriteAllText(path, "" + health);
}
else
{
File.Delete(path);
File.WriteAllText(path, "" + health);
}
}
In the other Script :
public int health = 1000;
public string health0;
public string path = Application.dataPath + "/Datas/data";
public GameObject healthbar;
void Update()
{
Int32.TryParse(health0, out health);
File.ReadLines(path);
if (health <= 600)
{
healthbar.SetActive(true);
}
else
{
if (healthbar.activeInHierarchy == true)
{
healthbar.SetActive(false);
}
}
}
You can access scripts from other scripts just by getting the script component (like any other component). Lets say you have a game object A with an attached script ScriptA and also a game object B with a script ScriptB. To access ScriptB from ScriptA, you would need to:
class ScriptA : Monobehaviour {
void Method() {
GameObject b = GameObject.Find("B"); // get somehow a reference to B
ScriptB scriptB = b.GetComponent<ScriptB>(); // get access to the script
// now you can access all public stuff from the script
scriptB.publicAttribute ...
scriptB.publicMethod() ...
}
}
For such runtime logic like you have with the healthbar, you should not use the filesystem. This is really an unnecessary detour.

Unity set UI text from other gameobject script C# [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I have 3 different scripts.
GameController
PlayerController
DestroyOnContact
GameController
public class GameController : MonoBehaviour {
public static Text scoreText;
void Start()
{
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while(true)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazardSmall, spawnPosition, spawnRotation);
//SpawnHazard();
yield return new WaitForSeconds(spawnWait);
}
}
PlayerController
public static float score = 0;
DestoyOnContact
void OnTriggerEnter(Collider other)
{
if (other.tag == "PlayerBolt")
{
PlayerController.score++;
Debug.Log(PlayerController.score);
GameController.scoreText.text = "Score: " + PlayerController.score;
Debug.Log(GameController.scoreText.text);
}
Destroy(other.gameObject);
Destroy(gameObject);
Problem
When I run my game and shoot the object that uses the DestroyOnContact script, the PlayerController.score++ works and I have debugged it. But trying to set the scoreText in GameController does not work. This results in neither the player shot nor the object being shot destroy.
I get the exception:
NullReferenceException: Object reference not set to an instance of an object
I have tried using:
GameObject gogc = GameObject.Find("GameController");
GameController gc = (GameController)gogc.GetComponent(typeof(GameController));
Followed by:
gc.scoreText.text = "Score: " + PlayerController.score;
Which yields the same result. What am I missing?
Hierarchy:
I would recommend that you don't have the text as a static class as you then can't set it through the inspector.
Instead make a public static instance GameController.
Then in your Awake method of the GameController set instance = this;
You can then call that object by saying GameController.instance.ScoreText.text, remember that your ScoreText should NOT be static.
The reason i put it in the Awake method is to ensure it gets set early in the games lifecycle.
Feel free to ask questions.

interconnecting scripts in unity3D using the preprocessor [duplicate]

I've searched around and I just can't get this to work. I think I just don't know the proper syntax, or just doesn't quite grasp the context.
I have a BombDrop script that holds a public int. I got this to work with public static, but Someone said that that is a really bad programming habit and that I should learn encapsulation. Here is what I wrote:
BombDrop script:
<!-- language: c# -->
public class BombDrop : MonoBehaviour {
public GameObject BombPrefab;
//Bombs that the player can drop
public int maxBombs = 1;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space)){
if(maxBombs > 0){
DropBomb();
//telling in console current bombs
Debug.Log("maxBombs = " + maxBombs);
}
}
}
void DropBomb(){
// remove one bomb from the current maxBombs
maxBombs -= 1;
// spawn bomb prefab
Vector2 pos = transform.position;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
Instantiate(BombPrefab, pos, Quaternion.identity);
}
}
So I want the Bomb script that's attached to the prefabgameobject Bombprefab to access the maxBombs integer in BombDrop, so that when the bomb is destroyed it adds + one to maxBombs in BombDrop.
And this is the Bomb script that needs the reference.
public class Bomb : MonoBehaviour {
// Time after which the bomb explodes
float time = 3.0f;
// Explosion Prefab
public GameObject explosion;
BoxCollider2D collider;
private BombDrop BombDropScript;
void Awake (){
BombDropScript = GetComponent<BombDrop> ();
}
void Start () {
collider = gameObject.GetComponent<BoxCollider2D> ();
// Call the Explode function after a few seconds
Invoke("Explode", time);
}
void OnTriggerExit2D(Collider2D other){
collider.isTrigger = false;
}
void Explode() {
// Remove Bomb from game
Destroy(gameObject);
// When bomb is destroyed add 1 to the max
// number of bombs you can drop simultaneously .
BombDropScript.maxBombs += 1;
// Spawn Explosion
Instantiate(explosion,
transform.position,
Quaternion.identity);
In the documentation it says that it should be something like
BombDropScript = otherGameObject.GetComponent<BombDrop>();
But that doesn't work. Maybe I just don't understand the syntax here. Is it suppose to say otherGameObject? Cause that doesn't do anything. I still get the error : "Object reference not set do an instance of an object" on my BombDropScript.maxBombs down in the explode()
You need to find the GameObject that contains the script Component that you plan to get a reference to. Make sure the GameObject is already in the scene, or Find will return null.
GameObject g = GameObject.Find("GameObject Name");
Then you can grab the script:
BombDrop bScript = g.GetComponent<BombDrop>();
Then you can access the variables and functions of the Script.
bScript.foo();
I just realized that I answered a very similar question the other day, check here:
Don't know how to get enemy's health
I'll expand a bit on your question since I already answered it.
What your code is doing is saying "Look within my GameObject for a BombDropScript, most of the time the script won't be attached to the same GameObject.
Also use a setter and getter for maxBombs.
public class BombDrop : MonoBehaviour
{
public void setMaxBombs(int amount)
{
maxBombs += amount;
}
public int getMaxBombs()
{
return maxBombs;
}
}
use it in start instead of awake and dont use Destroy(gameObject); you are destroying your game Object then you want something from it
void Start () {
BombDropScript =gameObject.GetComponent<BombDrop> ();
collider = gameObject.GetComponent<BoxCollider2D> ();
// Call the Explode function after a few seconds
Invoke("Explode", time);
}
void Explode() {
//..
//..
//at last
Destroy(gameObject);
}
if you want to access a script in another gameObject you should assign the game object via inspector and access it like that
public gameObject another;
void Start () {
BombDropScript =another.GetComponent<BombDrop> ();
}
Can Use this :
entBombDropScript.maxBombs += 1;
Before :
Destroy(gameObject);
I just want to say that you can increase the maxBombs value before Destroying the game object. it is necessary because, if you destroy game object first and then increases the value so at that time the reference of your script BombDropScript will be gone and you can not modify the value's in it.

how to make the GameObject have a parameter in unity (c#)?

please help me how to get the value of "currentPeople.timeCount;"
for example i have a script:
public class BuildingPlacement : MonoBehaviour
{
public GameObject currentPeople;public int DelayTime;private int timeCount;
}
if i want to say that
DelayTime = currentPeople.timeCount;
i try this code below and it says nullreferenceexception object reference not set to an instance of an object:
DelayTime = (BuildingPlacement)currentPeople.GetComponent(typeof(BuildingPlacement).timeCount);
How do I get the value of currentPeople.timeCount ? is it possible?
You can't add a variable to a GameObject as mentioned in your original question. It is very likely you want to add the script to the GameObject which also makes the timeCount variable available to that GameObject.
If that's the case then select the currentPeople GameObject and drag the BuildingPlacement script to it in the Editor. This is called attaching script to a GameObject. You can also do this via code with:
currentPeople.AddComponent<BuildingPlacement>();
To access the timeCount variable that is in the BuildingPlacement script which is attached to the currentPeople GameObject:
int value = currentPeople.GetComponent<BuildingPlacement>().timeCount;
It seems like you are lacking the basic knowledge of Unity. You can start from here.

Why am i Getting NullReferenceException when trying to create a HealthPack in Unity C#? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Ok guys and gals I'm having an issue again with some code. Basically once I start and it attempts to create a Health Pack it's throwing an error that:
NullReferenceException: Object reference not set to an instance of an object
HealthSpawnerScript.Update () (at Assets/Scripts/HealthSpawnerScript.cs:31)
below is the code i'm running. The gameobject PlayerController houses a method used to return Player Health named PlayerHealth(). In awake I set playerController to find the script and method I'm after. Then in update i'm trying to call the method and assign it to a variable for use in the script later. I know this should be simple but i'm having a brain fart guys.
public PlayerController playerController;
private int healthHolder;
void OnAwake()
{
playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();
}
// Use this for initialization
void Start ()
{
//set healthExist to false to indicate no health packs exist on game start
healthExist = false;
//playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();
}
// Update is called once per frame
void Update ()
{
healthHolder = playerController.PlayerHealth();
There is no Unity callback function named OnAwake. You are likely looking for the Awake function.
If that is fixed and your problem is still there, you have to seperate your code into pieces and find out what's failing.
playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController> ();
should be changed to
void Awake()
{
GameObject obj = GameObject.Find("PlayerHealth");
if (obj == null)
{
Debug.Log("Failed to find PlayerHealth GameObject");
return;
}
playerController = obj.GetComponent<PlayerController>();
if (playerController == null)
{
Debug.Log("No PlayerController script is attached to obj");
}
}
So, if GameObject.Find("PlayerHealth") fails, that means there is no GameObject with that name in the scene. Please check the spellings.
If obj.GetComponent<PlayerController>(); fails, there is no script called PlayerController that is attached to the PlayerHealth GameObject. Simplify your problem!

Categories