I’m trying to create a script where function update finds the main camera, then childs the current object to it (The object the contains this script), but I’ve run into a problem. If I change transform.parent to gameObject.parent, it finds the camera, but doesn’t parent the object. If I do transform.find, the whole thing doesn’t work at all. Is there something that I can use to replace gameObject that is compatible with transform.parent? Here is the script:
var cecked = gameObject.Find(“Main Camera”).GetComponent(HoldSend).holding;
transform.parent requires a Transform reference, and you should use GameObject.Find instead of gameObject.Find (GameObject is the class name, while gameObject is a property). But it’s much faster and easier to get the main camera reference from the variable Camera.main:
function Update(){
var cam: Camera = Camera.main; // get a Camera reference to the main camera
cecked = cam.GetComponent(HoldSend).holding; // copy holding to cecked
if (cecked){
transform.parent = cam.transform;
} else {
transform.parent = null;
}
}
Better yet, if your main camera is always the same, save a reference to its script HoldSend at Start and use it in Update:
private var holdSendScript: HoldSend; // reference to the HoldSend script
function Start(){
holdSendScript = Camera.main.GetComponent(HoldSend);
}
function Update(){
if (holdSendScript.holding){
transform.parent = Camera.main.transform; // child to the camera's transform
} else {
transform.parent = null;
}
}
You should try to not find objects each frame, it’s extremely resource heavy so try to move away from that type of habit. Instead cache your components. HoldSend could for instance be cached and accessed at any point.
Example:
private var cameraTransform : Transform;
private var cameraHoldSend : HoldSend;
function Start () {
cameraTransform = Camera.main.transform;
cameraHoldSend = cameraTransform.GetComponent(HoldSend);
}
function OnMouseOver () {
if (cameraHoldSend.holding)
transform.parent = cameraTransform;
else
transform.parent = null;
}
For the record you’re also able to access the main camera through Camera.main, where you can access any derived components.