double check.

Hi I have an intermediate scripting question.

If I have a random number of objects who I want to set the positions of at start. Where by the positions are all in line with each other so pos1 = pos1, pos2 = pos1 + 3 units, pos3 = pos2 + 3 units…

for (i = 0, i < objectNumber, i ++)
{
pos = rootPos * i;
object_.transform.position = (pos*);
}*
Would that make sense? Will I be able to access pos in other functions? I am thinking this might not even be necessary since I may only have 5 objects, but I am thinking about saving space in the inspector and extra lines of code.
I know I think I understand and know these answers, but I just want to double check.
Thanks._

More specifiaclly I have this…
it is a sample bit of my code.
In it, I am choosing my acitve player from x number that exist. Almost like an angry birds scenario. The trouble with me, is that the number of “birds” can vary. So this script is perfect if there is 3 birds. And if I wanted I could adjsut it to work for 5. But what if it were 500???

I know I should be using but I want to get a feel for this since this is two fold.
Step1. I choose my hero.
Step2. I load my hero (change its position via iTween)
Step3. All heros in waiting are moved up a position in waiting (like baseball on deck).
So with that, if anyone has some spare time and wouldn’t mind working this through with me I would appreciate it.
Thanks.
```
*function chooseHero()
{
yield WaitForSeconds(1);

if(heroCount >= heroTurns)
{
	///this mean level is over. 
	//so, load score. ers.
	print("heroManager: loadScore.round over.");
	return;
}
			
print("heroManager: chooseHero();");
heroCount++;
print("heroManager: heroCount " + heroCount);
if(heroCount == 1)
{
	activeHero = hero1;
	print("heroManager: 1 activeHero.name " + activeHero.name);
	loadHero();
	return;
}
else if(heroCount == 2)
{
	activeHero = hero2;
	print("heroManager: 2 activeHero.name " + activeHero.name);
	loadHero();
	return;
}
else if(heroCount == 3)
{
	activeHero = hero3;
	print("heroManager: 3 activeHero.name " + activeHero.name);
	loadHero();
	return;
}				

}
function loadHero()
{
print(“heroManager: loadHero();”);
///loads active hero into scene position
var rotationAmount : Vector3 = Vector3(0, 0, 360);
iTween.MoveTo(activeHero.gameObject, iTween.Hash(“position”, loadPos, “time”, 3, “easeType”, iTween.EaseType.easeOutCubic));
iTween.RotateAdd(activeHero.gameObject, rotationAmount, 2.5);
//get compoenet of the charctrls of activeHero and camera. These will allow movement ctrls to be applied.
heroCtrlr = activeHero.GetComponent(CharacterController);
cameraCtrlr = Camera.main.GetComponent(CharacterController);

///load waiting heros into position 1 over. 
if(heroCount == 1)
{	
	iTween.MoveTo(hero2.gameObject, heroWaitPos1, 2);
	iTween.MoveTo(hero3.gameObject, heroWaitPos2, 2);		
}
else if(heroCount == 2)
{	
	iTween.MoveTo(hero3.gameObject, heroWaitPos1, 2);		
}
	

yield WaitForSeconds(1.5);
heroIsLoaded = true;

}*
```

This is very easy to solve with an array or list. You are using UnityScript so the built-in Array data structure will work just fine for what you want.

// Unity inspector can only see regular arrays[] but not dynamic UnityScript Arrays.
// So we declare a regular array[] and assign our list of hero game objects in the inspector
var heroes : GameObject[];
// then we use an Array() class to easily manipulate the list of hero game objects
// yes, it is a bit redundant, but it makes the code incredibly simple.
private var waitingHeroes : Array;

function Start()
{
// we want to use the easy array manipulation functionality built-in to UnityScript
// so here we copy the regular array[] data items in to an Array data structure.
    waitingHeroes  = new Array(heroes);
}

function Update()
{
// this is just test code to load up the next hero
    if (waitingHeroes.length > 0)
    {
        var eagerHero : GameObject = LoadHero();
        ShuffleUpHeroes();
    }

}

function LoadHero() : GameObject
{
    // let's pull up the first hero in the array that is waiting for us
    var newHero = waitingHeroes.Pop();
    // display its name, do some other processing with our new hero
    print(newHero.name);

    return newHero;
}

function ShuffleUpHeroes()
{
    // our Array() of waiting heroes at this point probably has one less hero in it
    // we want all of the remaining heroes to move along a bit to show they are eager
    // to be thrown through the air in a glorious bone-crushing cascade of phospoherescence,
    // a glowing ball of flame, a testament to their godliness and piety!
    for (var i : int = 0; i< waitingHeroes.length; i++)
    {
        iTween.MoveTo(waitingHeroes[i], new Vector3(10 * i, 0, 0), 2);
    }

}

I could have simplified and used a native .NET array and the RemoveAt method, but didn’t feel like it. :slight_smile: So many ways to skin things.

Thank you Justin,
I will be going over this.

Cheers!!!

Ok great Justin,
I have gone thru but have run into one stumbling block.
That is, eagerHero as you have defined it.

When I run thru the script, eagerHero becomes the next object “popped” off the “stack” (correct terminology?). Anyhow, that works fine, but I need the eagerHero to be a Class var in that I need to access him continually, not only throughout this script but also others.

So a couple of things…
A. how do I make eagerHero a class var
B. the way you phrased this…

var eagerHero : GameObject = LoadHero();

I do not get it. You declare eagerHero to be a GameObject then equate it to a function Loadhere(). How can an object be a function. If that is right.

Thanks for all your help this is working extraordinarily and you sir may have been the straw that broke the camels back in terms of my finally getting into using arrays.

So Cheers!

LoadHero returns a GameObject. You’re not setting it to the function, you’re setting it to what the function returns to you.

If you need to access it from other scripts then making it a “class var” (I assume you mean static) is not the correct solution. Making it public or creating a public function to give it to another script is the correct solution.

Yes, when I print(“eagerHero.name” + eagerHero.name);
I get that, the objects name.
However, there is then a function titled and called as …

function LoadHero() : GameObject

By doing this, I am saying what exactly?

You’re creating a function called LoadHero that returns a GameObject. I’m not really sure how else to put it. These 2 statements are equivalent (from a results perspective)

var foo : GameObject = new GameObject();
var foo : GameObject = CreateObject();

function CreateObject : GameObject {
    return new GameObject();
}

Oh so,
var eagerHero : GameObject = LoadHero();
is just like creating a class var (a class var I define as a var created at the top of the script, accessible throughout the script). Except the object is created in the function… LoadHero() and with in that function you define what it is and if you want, its attributes?

If that is right, in the example…

function LoadHero() : GameObject
{
    // let's pull up the first hero in the array that is waiting for us
    var newHero = waitingHeroes.Pop();
    // display its name, do some other processing with our new hero
    print(newHero.name);
    return newHero;

}

I have defined a new var newHero. Which is the object at the top of the waitingHeroes stack. Correct?

If that is correct, just two other things…

  1. how can I access newHero from outside this function?
    and 2. forgive me for asking but…
return newHero;

…what does that mean?
I am only use to

return;

You should do some reading on methods and returning values from them.

This code means that LoadHero needs to return a GameObject to whatever called it. It doesn’t need to create it (it could go get one from somewhere else) but it needs to return one.

function LoadHero : GameObject

This actually returns the value to the caller and stops execution of the method at that point.

return newHero;

When you say “access newHero outside this function” that’s exactly what returning the value to the caller does for you.

and in this case the caller would be…?

and when you say the function LoadHero() : GameObject
needs to return a GameObject, I am uncertain what you mean by this.

In my mind, when I return something, I am returning a value. Usually my returns, I read from the console (bad example probably) but this is something that occurs inside the function, say a count for instance. I can not see at the moment how the function needs to return a GameObject value.

Whatever calls the function. In the example Justin provided it was the declaration of a variable called eagerHero on line 20.

Okay let’s take this from the top.

If you remember in an earlier thread you made (a couple of months ago), I mentioned that functions are declared as variables, in the sense that they always have a type. The folly of Unityscript is the fact that you don’t need to specifically declare the type of a function when you declare it, since Unity understands its type through context. However, you can, and this is what the above posters did. Let’s talk with examples.

Just like you can declare a variable of type int, you can also declare a function of type int. The syntax is the following :

var thisVariable : int = 5;

function ThisFunction ( ) : int {
      
          return 5;

}

In this example, thisVariable is a variable of type integer, and ThisFunction is a function of type integer since it returns an integer value of 5.

Note the " : int " after the function’s argument field. This is how we tell Unity what type of function this one is. Also note that in Unityscript we don’t have to do this. Since this function returns 5, Unity assumes it’s an integer function.

So what does return does? The return keyword breaks the function’s execution and returns a result. If you simply type

return;

you return nothing. Likewise you can return any value type you want, for instance

return transform;

What you do with the returned value is up to you. For example we can type

ThisFunction();

And it will do nothing, since we don’t handle the returned value (5). However, we can do

var result = thisVariable+ ThisFunction();
print(result);

which will print 10, since thisVariable equals 5 and ThisFunction returns 5.

I hope you get the grip of what goes on here. So how do we know what type of function our function is? We can check the return. If our function returns a gameObject value, its type is GameObject. If it returns transform, its Type is Transform. If it has a yield, it’s assumed to be a coroutine and cannot return a value, and as long as you have a yield statement in the function’s code, its type is always IEnumerator. If it doesn’t contain a yield and does not return anything, its type is void.

var result = thisVariable+ ThisFunction();

so by declaring a function as a type, are we giving us the flexibility to perform a massive calculation and then use it as a var to plug into other values? is this the benefit of doing this?

It’s not a matter of benefit, as much as a matter of OO logic and code management. Check for example the function I posted on the wiki on scaling the GUI :

The scaledRect( ) function is a function of type Rect. Since it returns a normalized Rect object, it can be used instead of the Rect constructor. This function allows us to avoid having to calculate all values of a Rect related to the Screen dimensions over and over on every GUI element manually. We simply pass the variables x,y,width,height, the function changes their values according to the Screen dimensions and returns us a new Scaled Rect to use on our GUI elements. If I were to declare this function (something I would be required to do if I was using C#), I’d have to declare it as

function scaledRect ( x : float, y : float, width : float, height : float) : Rect

The benefit of doing it is that it returns something to you. Your use case will vary. For example - GameObject.AddComponent returns the component that you just added so you don’t have to do AddComponent and then GetComponent right away if you need access to it. Mathf.Abs returns the absolute value of the number you give it. GameObject.Find() returns a GameObject. It isn’t necessarily a “massive calculation” it’s just what that method is designed to do.

Interesting.
So would this be handy in a game where the camera is zooming in and out? changing position?

Also, you mention.

A Rect constructor would be any class var I create at the top of script? And if so, I can not see how, given your example how in the OnGUI for instance, it would constantly have to regenerate, or check the values. I can not see how it is any different from have a class var declared prior to game start.

And thanks, this is useful.

ok, but I am just trying to see its benefit over declaring a class var at beginning of script and using it throughout. Or is there no benefit and just a different way to code?

It’s not a question of benefit versus no benefit. It’s a question of design.

GetComponent returns a Component. GameObject.Find() returns a GameObject. Is there a benefit to it doing that? No, they are designed to do that.

Well it is not the result I mean. More the method.