- Home /
How to reference another script and call a function in C# ?
So in a script script1 I have:
public void Follow(GameObject followTarget, bool snap = false)
{
Follow(followTarget.transform);
}
How can I reference this in script2 and assign a GameObject to it?
I found tutorials and examples online but I'm really struggling
Answer by Hoeloe · Nov 16, 2013 at 12:15 PM
You need an instance
of the script that you can reach from script2
. You can do this by either having a field of type script1
that you set from the inspector (`public script1 script;`), or you can use the GetComponent
method to grab it automatically.
From there, it's a simple case of writing: script.Follow(...)
and filling in the arguments as necessary.
As an aside, I recommend using CamelCasing for class names (e.g. MyScript1
instead of myscript1
). It helps to differentiate them from variables.
Instancing uses more memory, GetComponent uses more CPU time. So it's a trade off (in large projects)
Of course, but if you don't have an instance, it is not possible to call a non-static method. If your instance already exists, then you're just paying for another pointer, which is a $$anonymous$$imal use of memory.
BadAssGames has written one in the other answer. If you add the public
modifier to both of the variable declarations, and remove the line defining script1
, then you can declare those variables in the inspector.
I tried it replacing the example I gave with the actual script name and the object name in my scene (which is tagged as player): RtsCamera RtsCamera; GameObject Player_01;
void Start()
{
RtsCamera = FindWithTag("Player").GetComponent<RtsCamera>();
RtsCamera.Follow(RtsCamera, false);
}
and unity say that a namespace can only contain types and namespaces declarations 3 times and 'global'Assets/Scripts/Camera/RtsCamera/Scripts/RtsCamera.cs(16,14): error CS0101: The namespace global::' already contains a definition for
RtsCamera'
what Am I doing wrong ?
Answer by BadAssGames · Nov 16, 2013 at 12:18 PM
Script1 script1;
GameObject someGameObject;
void Start()
{
script1 = FindWithTag("SomeTaggedGameObject").GetComponent<Script1>();
script1.Follow(someGameObject, false);
}
Your answer
Follow this Question
Related Questions
How can I call a method from another script? 3 Answers
How to call a function from another script without referencing it? 1 Answer
call function with same name + number 1 Answer
Call a Function from another Script 1 Answer
Refin' another script in relation to speed, and not tacking from using the Update? 1 Answer