- Home /
Accessing a value in a script attached to another game object
I am trying to access a variable stored in a script attached to another game object.
I seam to be able to access the script with this line Component theScript = OBJhit.GetComponent(opponentScript); However, when I try to change the value stored in that script (value) it turns red and I get the following error - Expression denotes a type where variable value or method group was expected.
Could anyone point me in the right direction?
if (Physics.Raycast (transform.position, fwd, out hit, 20)) {
OBJhit = hit.transform.gameObject;
if (OBJhit.tag == "opponent") {
Component theScript = OBJhit.GetComponent(opponentScript);
theScript.value = true;
}
}
Answer by jokim · Sep 09, 2014 at 01:13 PM
HarshadK had part of the answer right, but I am not sure the way you're using GetComponent is the right one. (Not sure because I believe there's 2 ways to use it)
The way I recommend using it is as a template function, here's how to call it :
opponentScript theScript = OBJhit.GetComponent<opponentScript>();
theScript.value = true;
Edit : After double checking, HarshadK had a working answer... I would still try this way and see if the result is any different.
re-Edit : third answer has me corrected : GetComponent("opponentScript") is the way to call it. (other than mine)
+1. This will generate a compile time error if the component is not found.
Answer by HarshadK · Sep 09, 2014 at 12:58 PM
Make your theScript variable of type of your script as below:
opponentScript theScript = OBJhit.GetComponent(opponentScript);
theScript.value = true;
Edit: Actually it should have been
opponentScript theScript = OBJhit.GetComponent("opponentScript");
Hi, I have done that, however, "theScript" on the next line is highlighted in red (im working in c# if that makes any difference)
Is your value variable a bool?
Judging by the name it looks to be an int or float.
Then I would just suggest to use proper names for your variables. It's a part of good coding practice.
Answer by bhartu · Sep 09, 2014 at 01:16 PM
GetComponent() has three overloaded methods.
if you are using GetComponent("string"), then you can write OBJhit.GetComponent("opponentScript");
or if you are using GetComponent(System.Type) then you have to write OBJhit.GetComponent<>();
Your answer
Follow this Question
Related Questions
insert script question 1 Answer
C# GetComponent Issue 2 Answers
How to get a variable value from another script(C#)? 1 Answer