AymAPandah
AymAPandah

Reputation: 13

How do I associate a C# object with a Unity gameobject?

I understand that Unity uses C# scripts in a component based way, but that doesn't work well enough in a lot of cases.

Heres an example: Say I have a turret class and a lazer class. They both inherit from an IShootable interface which implements a Shoot() method. I want to loop through all the IShootable objects in the scene and call Shoot(). Sounds simple enough but I don't necessarily want to add these scripts as components to gameobjects, but rather instantiate them the traditional C# way: Turret t1 = new Turret();

Basically, when I instantiate the C# object, I want to instantiate a unity gameobject and treat it nearly identically.

Im fairly amateur and I know theres no perfect answer to this. I just want a consistent way to handle this confusion and make it less messy.

Thanks !!!

Upvotes: 1

Views: 1705

Answers (2)

If you want an object to exist in the scene, then it must be a GameObject. There are no alternatives.

Now, its perfectly find to have your Turret and Laser objects not inherit from MonoBehaviour, but they'd have to be associated with something that is in the scene, somehow. And the only thing that exists in the scene are GameObjects.

  • Option A: Make a MonoBehaviour script that has Turret and/or Laser as properties of that behavior script. Loop over all game objects in the scene and get their MB component and call Shoot() on that, which calls Shoot() for its encapsulated Turret or Laser object.

  • Option B: Make your Turret and Laser scripts instantiate and store a reference to their associated GameObject. I do this, after a fashion, in one of the games I'm working on now.

Upvotes: 2

codename895431
codename895431

Reputation: 111

I'll venture to assume that you are talking about an observer pattern. Link: https://msdn.microsoft.com/en-us/library/ee817669.aspx and using Unity3d action and delegates: Link: https://unity3d.com/ru/learn/tutorials/topics/scripting/input-actions-and-delegate-pattern or using Unity3d Evetns. I do not have enough reputation to insert another link, but you can find a tutorial on Unity's site

Upvotes: -1

Related Questions