[email protected]
Topic Author
Posts: 19
Joined: 16 Jan 2019, 23:16

Gameobjects and components from codebehind

12 Aug 2021, 20:48

Is it impossible to get a reference to gameobjects and components from codebehind?

As in, NOT using Viewmodel

Thx in advance :)
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Gameobjects and components from codebehind

12 Aug 2021, 21:40

Can't you just use GameObject.Find() and then access the Component you need?
 
[email protected]
Topic Author
Posts: 19
Joined: 16 Jan 2019, 23:16

Re: Gameobjects and components from codebehind

13 Aug 2021, 10:11

I am so stupid, I had no idea you could do that. I keep forgetting that I am not in a real WPF-land, I am in Unity WPF-land so ofc I have access to Unity objects.
Damn this engine is epic. I love it!

Is this the fastest way to do it btw?
GameObject mainCameraGameObject = GameObject.Find("Main Camera");
mainCameraGameObject.GetComponent<MyComponent>();
It seems I have to first search the object, which in this case is the same object as NoesisEngine is a component of, so I thought maybe I didn't have to search through all the objects in Unity, which this does.
Can't I do something like
thisGameObject.GetComponent<MyComponent>(); ?
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Gameobjects and components from codebehind

13 Aug 2021, 10:31

If you have a MonoBehavior script attached to the "Main Camera" object where the NoesisView is also connected you can access it by calling GetComponent:
public class MyComponent : MonoBehavior
{
  void Start()
  {
    NoesisView view = GetComponent<NoesisView>();
    // view.Content is the root UI element in the XAML
    // ...
  }
}
From there you can access any element in the UI tree if that is what you are trying to do.
 
[email protected]
Topic Author
Posts: 19
Joined: 16 Jan 2019, 23:16

Re: Gameobjects and components from codebehind

17 Aug 2021, 12:48

Ok thx, but I meant from the code behind xaml file. Fx. UserControl, not a Monobehavior :)
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Gameobjects and components from codebehind

17 Aug 2021, 13:30

In that case you should use the GameObject.Find approach, that's the best I can think of.
Of course, if this is something you are going to do many times you should store the result of that search in your user control to do it only once.

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot], Semrush [Bot] and 29 guests