I am currently a very new user to unity and scripting but am diligently working through a variety of resources to help with my education.
Recently I was trying to find a way to make a spawned projectile not interact with a series of tagged objects. After a bunch of forum searching and trial and error I was able to solve the problem and apply a working piece of code.
function Start () {
ignoreCollision("InvisWall");
}
function ignoreCollision(tag : String) {
var objects = GameObject.FindGameObjectsWithTag(tag);
for (o in objects) {
if (o.GetComponent("Collider") o != gameObject)
Physics.IgnoreCollision(collider, o.collider);
}
}
This make the prefab projectile which this small script is attached not collide with any objects tagged “InvisWall”. My problem is I don’t understand some parts of this code, and can’t find a Unity reference that explains it. I can make the code work, but I don’t know why it works.
My questions:
How does the ‘for’ loop work and what does ‘o in objects’ refer to?
Why does the ‘if’ statement not have a ‘{’?
If someone can break this down for me it would be a helpful learning tool. It’s just a bit different from what I’ve seen so far and I wasn’t able to find help in the Unity Scripting Reference.
for (var o : GameObject in objects) will loop all GameObjects in objects, for example.
The if do not have a { ? It means the next line only will be executed in the case the if test is true (it saves you from writing { } for one line. Same goes for else.
if (test)
executed if test is true
line executed no matter what test value is
line executed no matter what test value is
Thank you for the reply. The answer to #2 was very good to know.
I am still somewhat confused by #1. Are you saying ‘(o in objects)’ is accepted shorthand for ‘(var o : GameObject in objects)’? If so, does that mean variables default to type GameObject when not declared?
The only reason I ask for additional clarification is (o in objects) does function in my code without error. The var isn’t declared, but if it’s shorthand then that makes sense.