I have been having trouble understanding how access of variables between scripts works in Unity. I thought I knew how, but after much trial and error, I am still getting errors. My pathfinding code is contained in one script, and my agent behavior code is contained in another. Because of this obstacle, I have been unable to have my agent respond to the path calculated by my pathfinding code.
For example, in the screenshot below, the console shows a path count and the index. I want the index to initialize to 1 less than the path count, which it currently is not doing.
I have already read a lot of Unity manuals and tutorials, but I suppose I need to read some more...
How are you trying to access things right now? For my project, I had to figure out how to reach things in one script from another too, so here's what worked for me.
ReplyDeleteIn mine, I have a Director object with a script A attached to it, and I'm trying to reach script B on a separate Camera object. Right now, my script A actually has a variable for that Camera object just called "cam1," so in script A I can use:
"ScriptB otherScript = (ScriptB) cam1.GetComponent()"
If you're not storing a reference to the other object, you can do something like
"ScriptB otherScript = (ScriptB) GameObject.Find(“OtherObjectName”).GetComponent()"
Once you've got the other script, you could just do something like "this.index = otherScript.pathCount - 1"
I don't know if that's helpful at all, but I got that working after struggling for a while. Also, there are some weird issues when one script is C# and the other is javascript. But that stuff gave me a headache, so I gave up and just stuck to C#.
Haha, I was going to say "You should talk to Dan/Ian/everyone else who is using Unity" but I see Dan already has a response for you :D
ReplyDeleteSorry I can't help much!
Hey Dan, thanks for the help. I actually had already tried all of those things and I was still getting an error. Miraculously enough, I ran the code again today and it updated the index the way I wanted it to, but I still need to fix some bugs to get it to follow the path. Thanks again.
ReplyDeleteI just realized that when my post got posted, it actually cut out the part of the code that was helpful. :P
ReplyDeleteIt should be "ScriptB otherScript = (ScriptB) cam1.GetComponent < scriptB > ()", without those spaces around the brackets. For some reason that got erased in my post.
Anyway, I guess it doesn't matter if you got it working, but yeah that's what had been driving me crazy.