- Home /
How to assign a Rectransform and a Transform component in C#?
Hy,
I want to assign a RectTransform component and also a Transform component into my script however when I play my game, it does not recognize the object I want to assign.
How can we explain that?
here is my script:
public RectTransform MenuContainer;
public Transform LevelPanel;
public Transform LevelPanel;
private void Awake()
{
//pour remettre la scene à jour à chaque réouverture du menu:
menuContainer = (RectTransform)gameObject.transform.Find("MenuContainer");
if (menuContainer == null)
{
Debug.Log("MenuConainer is null");
}
LevelPanel.transform.Find("LevelPanel");
if(LevelPanel == null)
{
Debug.Log("LevelPanel is null");
}
StoryPanel.transform.Find("StoryPanel");
if(StoryPanel == null)
{
Debug.Log("storypanel is null");
}
}
Thank You!
Answer by Hellium · Jun 26, 2020 at 06:40 PM
Please, take some time to read the documentation in order to understand how the functions work.
https://docs.unity3d.com/ScriptReference/Transform.Find.html
To be called on a Transform
instance, returns the child gameObject whose name has been provided as a parameter
https://docs.unity3d.com/ScriptReference/GameObject.Find.html
static method to return the first active gameObject whose name has been provided as a parameter
gameObject.transform.Find("MenuContainer")
will return the child gameObject of the current gameObject whose name is MenuContainer
. If your script is attached on a gameObject which does not have such child, gameObject.transform.Find("MenuContainer")
will return null
LevelPanel.transform.Find("LevelPanel");
won't do anything, either call gameObject.transform.Find("LevelPanel");
or GameObject.Find("LevelPanel").transform;
Since you are calling the find methods in Awake
, I believe the objects exist in the scene before you enter play mode. In this case, get rid of the Find methods and simply drag & drop the transforms in the inspector.