Tuesday, July 23, 2013

Programming Thought - Order and Execution

Let say that there's a Button and a GameObject Ball.

The GameDesigner wanted to Ball to move when the button was click.

The shortest method to do this would be

-------------------------
Button.cs//

void OnClick()
{
 GameObject ball = GameObject.Find("ball");
 ball.Translate(new Vector3(1,0,0));
}
-------------------------

End of story, simple right?

However, this would pose problems in extended coding.

-- The Ball isn't doing thing by itself --

When the Project became larger, there might be input from other sources that caused the ball to move.
If someone, other than the coder, have to search through the things that caused the movement, the most obvious action for the searcher would be to look at the ball itself.
However, if the ball itself doesn't contain the code, it will be a real hassle to figure out where it originated.

To solve this, Codes need to be separated into [Order] and [Execution]

[Order]
- The code that tell something else to do something, but does not do it itself.

-------------------------
Button.cs//

Ball ball;

void Start()
{
 /*If the referenced object will never be change during runtime, it would be
wiser to cached them at the start. Otherwise, the program will have to find it
every loop, thus slow down the program*/
  ball = GameObject.Find("ball").GetComponent<Ball>();
}

void OnClick()
{
 //the button ordered the ball to move, but did not execute the movement.
 ball.Move();
}

-------------------------

[Execution]
-  The code that actually do something

-------------------------

Ball.cs//

Transform thisTransform;
Vector3 moveVector;

void Start()
{
 //Cached transform so that it will not have to be searched every Loop
  thisTransform = this.transform;
 moveVector = new Vector3(1,0,0);
}

//Called from Button.cs
public void Move()
{
 thisTransform.Translate(moveVector);
}
-------------------------

In this case, the Ball itself is the one doing the execution.
It would also be a good idea to comment on where it was called from.

No comments:

Post a Comment