Find and assign GameObject to custom class.


I use C# scripting. And I need to assign to GameObjects script a different GameObject. Previously I did it just by dragging, but now I need it automatically be assigned. The problem is that I have like custom class “Skidmarks” and I get the following error - error CS0029: Cannot implicitly convert type UnityEngine.GameObject' to Skidmarks’

public Skidmarks skidmarks;

 void Start() {
skidmarks = GameObject.FindGameObjectWithTag("Skidmarki");

How to deal with this problem?


A script as attached to a game object is called a Component. So you are attempting to get the ‘Skidmarks’ component from the game object with the name ‘Skidmarki’. Assuming you are certain the game object with the ‘Skidmarki’ tag exists you can do:

 skidmarks = GameObject.FindGameObjectWithTag("Skidmarki").GetComponent<Skidmarks>();

If for some reason there is no game object wit the ‘Skidmarki’ tag in the scene, the above line of code will produce a null reference exception error.

You are trying to make a GameObject fit into a Skidmark. This is the equivalent of trying to make a ball fit in a square hole.

You need to first fin the GameObject, then you need to get the Skidmark component from it using GetComponent.

If you do not know how to use GetComponent, have a look at the scripting tutorial videos made by Unity.