Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 Bhanuka_Dassanayake · Jan 02 at 06:37 AM · compute shadercalculation

Compute Shader for Calculations? (like, find closet thing ???)

Hi, most people talking about compute shaders and say it can calculate more things @ once using GPU.

My problem is can I use it for find closet enemy to player, something like that?


 foreach(Transform potentialTarget in enemies)
         {
             Vector3 directionToTarget = potentialTarget.position - currentPosition;
             float dSqrToTarget = directionToTarget.sqrMagnitude;
             if(dSqrToTarget < closestDistanceSqr)
             {
                 closestDistanceSqr = dSqrToTarget;
                 bestTarget = potentialTarget;
             }
         }

can I use compute shader to do this (above), If I can do this. can you give example how to do it.

Comment
Add comment
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

1 Reply

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

Answer by andrew-lukasik · Jan 02 at 06:26 PM

You don't need a GPU to make this fast, necessarily. While GPU allows for massively parallel computations it comes with it's costs like: some additional complexity, data transfer/synchronisation considerations, DX11 required (or mobile equivalent, whatever that is). IJobParallelForTransform Burst-compiled job deals with this decently well too - good enough for your case maybe.

Test case: 1000 Transforms costs about 0.07 ms (aux thread) alt text alt text

FindClosestTransform.cs

 using UnityEngine;
 using UnityEngine.Jobs;
 
 using Unity.Entities;
 using Unity.Mathematics;
 using Unity.Collections;
 using Unity.Jobs;
 
 using Random = UnityEngine.Random;
 using BurstCompile = Unity.Burst.BurstCompileAttribute;
 
 public class FindClosestTransform : MonoBehaviour
 {
 
     [SerializeField] Transform[] _transforms = new Transform[0];
     TransformAccessArray _transformsAccess = default(TransformAccessArray);
     public JobHandle Dependency = default(JobHandle);
     NativeArray<float> _distances;
     NativeArray<int> _index;
 
     void Start ()
     {
         if( _transforms.Length==0 )
         {
             var parent = new GameObject( "test transforms" ).transform;
             _transforms = new Transform[ 1000 ];
             for( int i=_transforms.Length-1 ; i!=-1 ; i-- )
             {
                 _transforms[i] = new GameObject().transform;
                 _transforms[i].position = Random.insideUnitSphere;
                 _transforms[i].SetParent( parent , worldPositionStays:true );
             }
         }
         _transformsAccess = new TransformAccessArray( _transforms );
         _distances = new NativeArray<float>( _transforms.Length , Allocator.Persistent );
         _index = new NativeArray<int>( 1 , Allocator.Persistent );
     }
 
     void OnDrawGizmos ()
     {
         foreach( var t in _transforms )
             if( t!=null )
                 Gizmos.DrawIcon( t.position , "animationkeyframe" );
     }
 
     void OnDestroy ()
     {
         Dependency.Complete();
         if( _transformsAccess.isCreated ) _transformsAccess.Dispose();
         if( _distances.IsCreated ) _distances.Dispose();
         if( _index.IsCreated ) _index.Dispose();
     }
 
     void Update ()
     {
         Dependency.Complete();
         Debug.DrawLine( transform.position , _transforms[_index[0]].position );
 
         var job1 = new CalculateDistances{
             Position    = (float3) transform.position ,
             Distances    = _distances
         };
         Dependency = job1.Schedule( _transformsAccess );
         var job2 = new FindIndexWithLowestValue{
             Values    = _distances ,
             Index    = _index
         };
         Dependency = job2.Schedule( Dependency );
     }
 
     [BurstCompile]
     public struct CalculateDistances : IJobParallelForTransform
     {
         public float3 Position;
         [WriteOnly] public NativeArray<float> Distances;
         void IJobParallelForTransform.Execute ( int index , TransformAccess transform )
             => Distances[index] = math.distancesq( Position , transform.position );
     }
 
     [BurstCompile]
     public struct FindIndexWithLowestValue : IJob
     {
         [ReadOnly] public NativeArray<float> Values;
         [WriteOnly] public NativeArray<int> Index;
         void IJob.Execute ()
         {
             int lowestValueIndex = 0;
             float lowest = float.MaxValue;
             for( int i=0 ; i<Values.Length ; i++ )
             if( Values[i]<lowest )
             {
                 lowest = Values[i];
                 lowestValueIndex = i;
             }
             Index[0] = lowestValueIndex;
         }
     }
 
 }


gif-02012022-19-08-06-2.gif (134.4 kB)
screenshot-2022-01-02-190358.jpg (13.3 kB)
Comment
Add comment · Show 1 · 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 Bhanuka_Dassanayake · Jan 03 at 06:43 AM 0
Share

Thans Lot @andrew-lukasik

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.

Follow this Question

Answers Answers and Comments

133 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

Related Questions

Are OnGUI calculations cached? 1 Answer

How to save run-time variables to dictionary? 1 Answer

How do you calculate the rotation of a hexagon based on the six Vector3 points 0 Answers

Graphics.drawProcedural in normal render queue 1 Answer

RWTexture2D in Compute Shader on Android? 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