• 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
0
Question by benapprill · Dec 04, 2020 at 08:06 AM · dots

Create clickable ECS entity, WITHOUT authoring component from Editor

I can set up a GameObject cube, and convert it to an entity using authoring component scripts. With this, I can write a script that does a raycast on click. When I do this, the raycast works correctly.

However, I want to create that component in the script, and not have to use the authoring component conversion workflow.

The objects I am trying to spawn are spawned in random positions on each startup, so I don't want to have them all created in the hierarchy, just so they can be converted. How do I create an entity, WITHOUT conversion components in the editor, that will register the raycast?

Comment
Add comment · Show 3
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 · Dec 04, 2020 at 12:21 PM 0
Share

Which api are you using to execute raycast?

Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by benapprill · Dec 07, 2020 at 03:42 AM

andrew-lukasik had a great comment above.

By creating a "Bounds", using the "WorldRenderBounds" of each entity queried, an IntersectRay can be run to determine if the mouse-click intersected the entity.

 if (Input.GetMouseButtonDown(0))
         {
             var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 
             Entities.ForEach((Entity entity, in WorldRenderBounds bounds) => {
                 float3 center = bounds.Value.Center;
                 float3 extents = bounds.Value.Extents;
 
                 Bounds newBounds = new Bounds(center, extents);
 
                 bool haveHit = newBounds.IntersectRay(ray, out float distance);
 
                 if (haveHit)
                 {
                     Debug.Log("Click registered hit");
                 }
             }).Run();
         }
 }
Comment
Add comment · Show 3 · 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 andrew-lukasik · Dec 07, 2020 at 12:08 PM 0
Share

To make it more cpu-efficient you can also write it like this:

 // src: https://gist.github.com/andrew-raphael-lukasik/917046557baed6646c9fdc3b40671307
 using UnityEngine;
 using Unity.Entities;
 using Unity.$$anonymous$$athematics;
 using Unity.Collections;
 using Unity.Rendering;
 
 [UpdateInGroup( typeof(PresentationSystemGroup) )]
 public class SelectionSystem : SystemBase
 {
     public static event System.Action<Entity,Entity$$anonymous$$anager> onClick = (clicked,clickedEntity$$anonymous$$anager)=>
     {
         #if DEBUG
         Debug.Log($"{clicked} <b>clicked</b>");
         #endif
     };
     public static event System.Action<Entity,Entity$$anonymous$$anager> onDoubleClick = (clicked,clickedEntity$$anonymous$$anager)=>
     {
         #if DEBUG
         Debug.Log($"{clicked} <b>double-clicked</b>");
         #endif
     };
     const double k_double_click_threshold = 0.5f;
     
     public NativeQueue<(Entity entity,float distance)> _hits = new NativeQueue<(Entity,float)>( Allocator.Persistent );
     public NativeArray<(Entity entity,double time)> _clicks = new NativeArray<(Entity,double)>( length:2 , Allocator.Persistent );
 
     protected override void OnUpdate ()
     {
         if( Entity$$anonymous$$anager.Exists(_clicks[0].entity) )
         {
             var click = _clicks[0];
             var oldClick = _clicks[1];
             if( click.entity==oldClick.entity && (click.time-oldClick.time)<k_double_click_threshold )
                 onDoubleClick( click.entity , Entity$$anonymous$$anager );
             else
                 onClick( click.entity , Entity$$anonymous$$anager );
             _clicks[1] = click;
             _clicks[0] = ( Entity.Null , 0f );
         }
 
         if( Input.Get$$anonymous$$ouseButtonDown(0) )
         {
             var ray = Camera.main.ScreenPointToRay( Input.mousePosition );
             var hits = _hits;
             var hits_writer = _hits.AsParallelWriter();
             var clicks = _clicks.Slice();// alias
             double time = Time.ElapsedTime;
             
             Entities
                 .WithNone<Disabled,Prefab>()
                 // .WithAll<SELECTABLE>()// uncomment to enable this filter
                 .ForEach( ( in Entity entity , in WorldRenderBounds wrb ) =>
                 {
                     if( wrb.Value.ToBounds().IntersectRay(ray,out float distance) )
                         hits_writer.Enqueue( (entity,distance) );
                 })
                 .WithBurst().Schedule();
             
             Job
                 .WithName("select_best_click_candidate_job")
                 .WithCode( ()=>
                 {
                     Entity nearest = Entity.Null;
                     float dist = float.$$anonymous$$axValue;
                     while( hits.Count!=0 )
                     {
                         var hit = hits.Dequeue();
                         if( hit.distance<dist )
                         {
                             nearest = hit.entity;
                             dist = hit.distance;
                         }
                     }
                     clicks[0] = ( entity:nearest , time:time );
                 })
                 .WithBurst().Schedule();
         }
     }
 
     protected override void OnDestroy ()
     {
         _hits.Dispose();
         _clicks.Dispose();
     }
 
 }
 
 // <summary> Tag component to flag selectable entities. </summary>
 public struct SELECTABLE : IComponentData {}
avatar image andrew-lukasik andrew-lukasik · Dec 07, 2020 at 02:45 PM 0
Share

To use this SelectionSystem subscribe to one of it's events. Here is an example:

 using UnityEngine;
 using Unity.$$anonymous$$athematics;
 using Unity.Entities;
 using Unity.Transforms;
 using Unity.Rendering;
 public class LookAtDoubleClickedEntity : $$anonymous$$onoBehaviour
 {
     void OnEnable ()
     {
         SelectionSystem.onDoubleClick += OnDoubleClick;
     }
     void OnDisable ()
     {
         SelectionSystem.onDoubleClick -= OnDoubleClick;
     }
     void OnDoubleClick ( Entity entity , Entity$$anonymous$$anager entity$$anonymous$$anager )
     {
         var clickedTransform = entity$$anonymous$$anager.GetComponentData<LocalToWorld>( entity );
         Vector3 clickedPos = clickedTransform.Position;
         
         AABB clickedBounds = entity$$anonymous$$anager.GetComponentData<WorldRenderBounds>( entity ).Value;
         Vector3 clickedCenter = clickedBounds.Center;
 
         Debug.DrawLine( transform.position , clickedBounds.Center , Color.magenta , 5f );
         transform.rotation = Quaternion.LookRotation( clickedCenter-transform.position , Vector3.up );
     }
 }
avatar image andrew-lukasik · Dec 07, 2020 at 02:14 PM 1
Share

When working with RenderBounds it's very useful to be able to see them drawn in SceneView window. To enable just that add this magical line to your manifest.json:

"io.github.jonasdem.entityselection": "https://github.com/JonasDe$$anonymous$$/EntitySelection.git",

Very useful. Select an entity in EntityDebugger window and it will draw is bounds.

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

140 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

Related Questions

Label dots in between numbers (currency formatting) 2 Answers

How to determine which side of an object the player collided with? 2 Answers

Acessing static variable from Entities.ForEach 1 Answer

DOTS Grid-based generation question. 1 Answer

Where is com.unity.animation? 1 Answer


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