Cross Object/Script referencing is an important part of C# scripting within the unity environment. You often have to access one GameObject's references/components into another script. There are different ways to do cross-script referencing. In the below video, I have explained the simplest way to access one C# script variable from another C# script.
Generally, I don't like to do this thing as it creates a dependency on a script. While the best practice is to write loosely coupled code. Writing loosely couple code is a separate topic and this tutorial is for absolute beginners.
public class GameManager: MonoBehaviour
{
public GameObject player;
void Awake()
{
player = GameObject.Find("player");
player = GameObject.FindGameObjectWithTag("player");
}
}
Let's define the Pros/Cons of each option of assignment:
Option 1: Drag and Drop Object in Inspector
public GameObject player;//option 1 drag and drop
Pros:
1. Very Easy and simplest
2. No code is required for dynamic assignment
Cons:
1. Not supported in cross-scene reference.
2. Manual change requires if the assigned object gets changed or you apply the script again.
3. More objects mean more time required for manual assignment.
Option 2: Find with Name
player = GameObject.Find("player");
Pros:
1. Runtime assignment
2. No manual work is required.
Cons:
1. Limited only for a single unique name
2. If the gameobject name change then you have to change the name in the script (find method).
Option 3: Find with Tag Name
1. Runtime assignment
2. No manual work is required to accept tag assignments.
Cons:
1. Manual Assignment is required for tag name.
1. If the gameobject tag name is not assigned then, you are unable to find it.
Option 4: Find with GetComponent
1. Runtime assignment
Cons:
1. Limited only for the given object
Option 5: Assign with this
1. No external dependency is required
2. Clean and easy to use
Cons:
1. Script attachment is a must on the same game object
Option 6: Find with Type
player = FindObjectOfType<Player>().gameObject;
Cons:
1. Must need to create a script file for external dependency
2. Script attachment required
0 Comments