- Home /
Changing a variable on a different object
Ok, I realize that there are a bunch of other questions that have been answered about this, but none of those seem to work for me. I have player, a car, and a camera. The camera uses the Smooth Follow script to follow the player. The variable used for the target is this:
var target : Transform;
The car is supposed to be the target of the camera when a function is executed. The function is executing, but it is not able to find the variable. Here is my code for that:
var camm = Camera.main.GetComponent("SmoothFollow");
var trans : Transform;
camm.target = trans;
I dragged the car model onto the the trans cariable in the unity editor. When I do these errors:
UnityException: You are not allowed to call this function when declaring a variable.
get_main can only be called from the main thread.
ArgumentException: get_main can only be called from the main thread.
MissingFieldException: UnityEngine.Component.target
Any ideas? Thx in advance!
Nothing much visible from teh code you copy-pasted.. But just checking.. Are you calling teh Camera.main.GetComponent() from outside a function? If so, $$anonymous$$aybe you want to just declare it outseide the function and initialize it inside startup()..
Answer by FXBaconGames · Aug 19, 2014 at 10:23 PM
I figured it out! I had to use BroadcastMessage.
Answer by DBar · Aug 19, 2014 at 05:38 AM
1) Use SendMessage from the gameManager or something related to your game logic using OOP or pass the transform to a static variable inside the Smooth component.
2) If you use SendMessage(), the message has to have a reference inside the params to the Player transform or a gameobject acting as a center of camera in your case, inside the car for granularity.
3) The receiver, the camera object has to have an static variable acting as target.
4) You need to declare a method to set the variable.
Hint:
static var target : Transform;
Your objects has to communicate.
Try to refactor your code to use OOP and not just drag & drop.
Enjoy.
Your answer
Follow this Question
Related Questions
2D Camera Smooth Follow with Dynamic Offset 0 Answers
Smooth Follow Problem 1 Answer
Smooth camera follow return 1 Answer
Demons Souls Fall death Camera 1 Answer
custom SmoothFollow script camera position won't change 1 Answer