Tuesday, December 9, 2014

CSG Post 8: Living, Eating, Breathing by Reference

Up until very recently I never knew the true value of reference types. If you are not familiar with reference types, a reference type is a data type that stores the machine location of a piece of data instead of the data himself. The benefit of  this means that you can set this one data value from anywhere you have the reference. Another benefit is that it allows you to store and pass a lot of data without passing a lot of data. This particular benefit has been making my life a lot easier recently. On SOY I will often need to get data from a one object to another object. At first what I would to was assign a value directly using the get component method.

varINeed = targetObject.GetComponent<TargetScript>().desiredVar;

However a better way to do it is to just store a reference type of the object that I need access to.

var varINeed;

TargetScript  targetScript = targetObject.GetComponent<TargetScript>();

varINeed = targetScript.desiredVar;

This way is much much better because now you can also access any other data that you need from that object.

No comments:

Post a Comment