• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by dcmrobin · May 28 at 03:10 PM · gameobjectdotscommunicationconverting

Creating an entity from code, and then communicating with it from Monobehaviours


So first of all, I would like to spawn a GamObject, and then convert it to an entity, through code.


Then, since some pretty important scripts need to communicate with it, and the GameObject itself has one or two scripts on it, I would like the Monobehaviour scripts to be able to call functions (voids) that are in the GameObject (this GameObject would now be an entity) script(s).


I would love any help on this since I am spawning a lot of these GameObjects at once... and by doing that, I'm slowing down the performance.


Comment
Add comment · Show 8
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image andrew-lukasik · May 28 at 04:00 PM 0
Share

Your descriptions portrays OOP expectations. Entities are DOD territory so change in thinking is advised as well.

What I mean by that is you're not suppose to call functions on entities. Entities represent collection of data (data about player, enemy, tree, cube, collider, whatever). SystemBase are a place where you write what things happen to that data.

avatar image dcmrobin andrew-lukasik · May 28 at 05:03 PM 0
Share

Ah... thanks for replying... but do you know another way of making the performance better, while still being able to communicate with the objects I'm spawning? (they're chunks in a world that I'm wanting to make bigger)

avatar image andrew-lukasik dcmrobin · May 28 at 05:12 PM 0
Share

In ecs you communicate with entities by changing their data OR create dedicated entities that pass the message.

avatar image andrew-lukasik dcmrobin · May 28 at 05:22 PM 0
Share


I can help you with this but I have a very vague idea of what you want here. "chunk" and "to make bigger", without context, mean everything and nothing to me.


Sure there are ways to scale thousands of entities but I'm not sure where to begin without seeing more precise question or related code first.


avatar image dcmrobin andrew-lukasik · May 29 at 03:06 PM 0
Share

ahh so sorry! first things first. I have a marching-cubes-terrain world which, to make performance better, is split into chunks. (ask me for more info if that's not clear enough) but I want the world to be bigger, so I just increase the variable that controls the number of chunks spawning in the world. in turn, this decreases the game's performance. then I thought, the chunks are all individual GameObjects, so how about I download DOTS and all its packages, and then make them into entities to make the game faster! (I had experimented with DOTS before, and it made life so much easier) so, after trial and error, I got all the packages installed. only to realize that there was no way that I knew of to communicate with entities from normal GameObjects.

that's about all of it! ECS is a way that I know of, but I have absolutely no idea of how I set that up.

avatar image andrew-lukasik dcmrobin · May 31 at 07:23 AM 0
Share


From what you described I'm let to believe that you need a job system + Burst, not entities here. For example: https://github.com/Unity-Technologies/MeshApiExamples


Dozens of GameObjects doing computation-heavy work is not a conversion scenario where entities shine. Entities are great when there are thousands of GameObjects to replace, where every one of them was doing relatively little work (1000 * any tiny computation can still be a significant choke point).


avatar image andrew-lukasik dcmrobin · May 31 at 07:32 AM 0
Share

only to realize that there was no way that I knew of to communicate with entities from normal GameObjects.

This is not exactly true. You can communicate with entities, but not by calling their methods (OOP style) but by changing their data/state (DOD style).
Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by andrew-lukasik · May 31 at 12:06 PM


Here is a most basic example showing how you can communicate with a specific entity from a MonoBehaviour:


  1. Attach PlayerAuthoring & ConvertToEntity components to a capsule shape GameObject & make sure it's visible to main camera

  2. Attach PlayerController to an empty GameObject

  3. Hit play; capsule shape should move according to your Horizontal/ Vertical axis input.


PlayerAuthoring.cs

 using UnityEngine;
 using Unity.Entities;
 
 namespace Sandbox
 {
     public class PlayerAuthoring : MonoBehaviour, IConvertGameObjectToEntity
     {
         [SerializeField] int _index;
         void IConvertGameObjectToEntity.Convert ( Entity e , EntityManager dst , GameObjectConversionSystem cs )
         {
             dst.AddComponentData( e , new Player{
                 Index    = _index
             } );
             dst.AddComponent<HumanInput>( e );
         }
     }
 }


PlayerController.cs

 using UnityEngine;
 using Unity.Mathematics;
 using Unity.Collections;
 using Unity.Entities;
 using Unity.Transforms;
 
 namespace Sandbox
 {
     public class PlayerController : MonoBehaviour
     {
         [SerializeField] int _index;
         [SerializeField] float _speed = 5f;
         EndSimulationEntityCommandBufferSystem _commandBufferSystem;
         EntityQuery _query;
         void Start ()
         {
             var world = World.DefaultGameObjectInjectionWorld;
             var entityManager = world.EntityManager;
             _commandBufferSystem = world.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
             _query = entityManager.CreateEntityQuery( typeof(Player) , typeof(HumanInput) );
         }
         void Update ()
         {
             int numHumanPlayers = _query.CalculateEntityCount();
             if( numHumanPlayers!=0 )
             {
                 var cmd = _commandBufferSystem.CreateCommandBuffer();
                 var entityArray = _query.ToEntityArray( Allocator.Temp );
                 var playerArray = _query.ToComponentDataArray<Player>( Allocator.Temp );
                 for( int i=0 ; i<numHumanPlayers ; i++ )
                 {
                     Player player = playerArray[i];
                     if( player.Index==_index )
                     {
                         Entity entity = entityArray[i];
                         cmd.SetComponent( entity , new HumanInput{
                             Horizontal    = Input.GetAxis("Horizontal") * _speed ,
                             Vertical    = Input.GetAxis("Vertical") * _speed
                         } );
                     }
                 }
             }
         }
     }
 
     public struct Player : IComponentData
     {
         public int Index;
     }
 
     public struct HumanInput : IComponentData
     {
         public float Horizontal, Vertical;
     }
 
     [UpdateInGroup( typeof(SimulationSystemGroup) )]
     public partial class HumanInputSystem : SystemBase
     {
         protected override void OnCreate ()
         {
             base.OnCreate();
 
             RequireForUpdate( EntityManager.CreateEntityQuery( typeof(HumanInput) ) );
         }
         protected override void OnUpdate ()
         {
             float deltaTime = Time.DeltaTime;
             var camera = Camera.main;
             if( camera==null )
             {
                 Debug.LogWarning("main camera not found");
                 return;
             }
             var camTransform = camera.transform;
             float3 dirforward = camTransform.forward;
             float3 dirright = camTransform.right;
             
             Entities
                 .WithChangeFilter<HumanInput>()
                 .ForEach( ( ref Translation translation , ref Rotation rotation , in HumanInput input ) =>
                 {
                     float3 stepforward = new float3(dirforward.x,0,dirforward.z) * input.Vertical;
                     float3 stepright = new float3(dirright.x,0,dirright.z) * input.Horizontal;
                     float3 step = ( stepforward + stepright )*deltaTime;
                     translation.Value += step;
 
                     if( math.any(step!=0) )
                     {
                         float3 movdir = math.normalize(step);
                         rotation.Value = quaternion.LookRotation( movdir , new float3(0,1,0) );
                     }
                 } )
                 .WithBurst()
                 .ScheduleParallel();
         }
     }
 }


Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image dcmrobin · May 31 at 12:12 PM 0
Share

thanks alot!

avatar image dcmrobin · May 31 at 12:22 PM 0
Share

one problem though, I get an error that says: 'World' does not contain a definition for 'DefaultGameObjectInjectionWorld'

any idea what to do?

avatar image andrew-lukasik dcmrobin · May 31 at 12:40 PM 1
Share

Also, make sure you have no custom class named World as those will name-collide.

avatar image dcmrobin andrew-lukasik · May 31 at 12:43 PM 0
Share

ah I had a script named World

Show more comments
Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

250 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to communicate between scenes??? 2 Answers

Converting some C# pseudo code to UnityScript.... 1 Answer

Cannot see gameobjects in Unity editor (DOTS problem) 0 Answers

using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers

how to communicate with the target gameobject? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges