- Home /
Unity crashes when accessing a function of a script from another script
Hey guys! I'm trying to access a function of a script from another script. My first script EnterVehicle.cs calls the SetTarget function of FollowCamera.cs like this:
mainCamera.GetComponent<FollowCamera>().SetTarget(enteredCar);
SetTarget is declared as follows:
public void SetTarget(Transform _target)
{
target = _target;
}
Unity keeps crashing when I call SetTarget from my EnterVehicle script.
Unity has been really unstable since I updated: I don't get any runtime errors unity just freezes and I have to close it from the task manager.
Has anybody got an idea what I'm doing wrong? Thanks in advance, Cranberry
It's probable that you have created an infinite loop.
Attach $$anonymous$$onoDevelop to the process and pause it when it freezes to see where in your code the problem is happening.
Ok so I found out that it doesn't even get to 'target = _target;' unity just freezes when it gets to mainCamera.GetComponent.
I do not see any of my answers so i'll just use comments. Your method/class is not static so i think that you cant access it directly like you did. Try to first make reference to the FollowCamera script:
FollowCamer followCamera = mainCamera.GetComponent<FollowCamera>();
Then try to access your method like this:
followCamera.SetTarget(enteredCar);
Answer by Cranberry · Feb 09, 2014 at 03:03 PM
Stupid me! facepalm Forgot to assign the Transform for the vehicle in the editor. But I still got the problem that Unity just freezes instead of giving me a NullReferenceException.
Answer by DajBuzi · Feb 09, 2014 at 03:07 PM
I might be wrong with this but what i see is that your method is not static so you need a reference to the script object.
var camScript = mainCamera.GetComponent<FollowCamera>();
And then you can perform actions with your FollowCamera script.
camScript.SetTarget(enteredCar);
Your answer
Follow this Question
Related Questions
Declare Component type in GetComponent 2 Answers
Very simple component-access question 0 Answers
Can I access components scripts? 3 Answers
Painted Tree's Script Component 1 Answer