- Home /
How to correctly send a variable to another function?
I am trying to run a function in another script, outputting a particular variable to that function so that in the other script, it has that variable and can act on it as it needs to.
Here is the code that activates the function in the other script (which works, as it does the Debug.Log correctly):
setTankPathingScript.TPathingWhenSelected(selectedUnitNode);
And here is the code that is run:
public void TPathingWhenSelected(TileNode sN) {
Debug.Log("You have selected a tank!");
foreach (TileNode selctdInnerN in sN.nodeLinks) {
if (sN != null) {
selctdInnerN.tileTypeMask = TileNode.tileTypeMask.Giant;
Debug.Log("neighbour: " + selctdInnerN.name);
}
else
Debug.LogWarning("error: ",this);
}
}
}
I think it has something to do with the way I'm sending the 'selectedUnitNode' variable over to the other script and function, but I'm not sure.
I can't for the life of me work out why it keeps having the error. Somebody, please help!
Bah! Silly editor thing. Editing code to look correct, please wait.
edit 2: Coded adjusted to look proper.
I've realigned your lines to match the true code blocks. That's the reason why i always put the opening bracket in a new line ;) It's much easier to match opening and closing brackets.
I'm pretty sure it's a class ;) since a TileNode has "links" to other TileNodes. I don't think a TileNode is composed of other TileNodes ;)
Answer by MadDave · Jul 30, 2012 at 01:11 PM
The if statement looks wrong. If sN was null you'd get a crash in previous statement accessing sN.nodeLinks. Did you maybe mean
if(selctdInnerN != null)
Tried that, and it didn't work.
The 'Object reference not set to an instance of an object' error points me to the line:
foreach (TileNode selctdInnerN in sN.nodeLinks)
Could it be the other script that's sending the variable across from the other script?
That can only mean that the parameter you are sending ("sN") is null. Can you post the calling code?
Either sN or sN.nodeLinks is null.
Try this:
if (sN == null || sN.nodeLinks == null)
{
Debug.LogError("!!ERROR 1!!");
return;
}
foreach (TileNode selctdInnerN in sN.nodeLinks)
{
if (selctdInnerN == null)
{
Debug.LogError("!!ERROR 2!!");
continue;
}
// rest of your code here
}
There are only two things that could cause this error:
either sN is null
or sN.nodeLinks is null
So as $$anonymous$$adDave said, check your variable you're passing to the function. If you want to be able to pass null, handle this case correctly inside the function. If it's null you can't access a member since the object doesn't exist.
GetComponent retrieves an existing component attached to your gameObject. It does not add this component. If the component does not exist then null is returned.
If you need to attach a new component, use AddComponent ins$$anonymous$$d of GetComponent.