- Home /
Trouble referencing variables inside of a script (C#)
Hey, i have two scripts, one called targeting which has the public game object "attackingCity" in it. In the other script, i have a private variable of type targeting called "targetRef". I have set the attackingCity variable to cityE and when I Debug.Log it from the targeting script it confirms this. When i try and call this city from the other script using Debug.Log(targetRef.attackingCity); it throws a null reference exception at me.
you need to show the code, no telling what you're doing wrong
private targeting targetRef; targetRef.attackingCity = this;
That's all the code there is.
Answer by Montraydavis · Nov 01, 2012 at 04:32 PM
You are not properly settings the refernce. Perhaps post your method here, but, it should look something like this
var TargetReference : GameObject ;
function Start ( )
{
TargetReference = GameObject.Find ( "ObjectName" ) ;
//OR
TargetReference = GetComponent ( ScriptComponentNameWithout.CS ) ;
}
targetRef = GetComponent("targeting");
That's the line where I'm trying to set the target reference and right now it's saying that i can't convert a type component to a type targeting. When I add 'as targeting' to the end in order to cast it, my Debug.Log(targetRef) returns null. Whats going on? I'm in C# btw
C# and JS don't really differe here, except declaring variables.
Just set the Type to the type that it is . . IE
If it's a GameObject
GameObject TargetReference = blaaa. ;
ScriptName TargetReference = blaaa. ;
EDIT: I've resolved part of the issue: when i Debug.Log(targetRef) now it logs "scriptHolder (targeting)" (scriptHolder is the object containing the targeting script.) However, when i try to do targetRef.variableName, it throws up an error that 'UnityEngine.Component doesn't contain a definition for variableName'
simply put, just get rid of the quotes:
targetRef = GetComponent(targeting); // no quotes
this returns a type of "targeting" rather than "Component", as you want
also, maybe declared wrong, try:
targeting targetRef = gameObject.GetComponent...// ...etc
It just doesn't work. i had to make the variable of type component because there was a conversion error and typecasting wouldn't work. I need quotes because the GetComponent only takes a string. Check the edit on the previous comment.