Search Unity

Will there be a tut for the 2019 version...

Discussion in 'Entity Component System' started by Shuhair_jr, May 9, 2019.

  1. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    Tried to use this version for first time and the got a 1fps for my character system....... :p...
     
    Last edited: May 10, 2019
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    You mean Unity 2019.x? if so, this is wrong forum section.
     
  3. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    Thanks where sjould I put it....
     
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
  5. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    Oh hold on, you are asking for tutorials/samples for ECS yes?
    Correct me please, if I am wrong.
     
  6. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    Can I move the thread to there without creating an new one...?
     
  7. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    Yes
     
  8. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    Well then, which tutorial / samples you are trying to run?
    Does Unity editor itself works smoothly?
    What are your work station parameters?
     
  9. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    No unity editor do not response to any ket but the scene plays my player idle animation in 1 - 5fps...
    I have to close the unity editor from task manager... Im using unity official tut and thirdperson assets
     
    Last edited: May 10, 2019
  10. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    Does Unity 2018.x or 2017.x works on your work station?
     
  11. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
  12. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    Ill share my ecs character system... If it would help.... I have also found that getentities, inject and more has been depreciated.... the new functions are implimented wrong in my code I think...
     
  13. psuong

    psuong

    Joined:
    Jun 11, 2014
    Posts:
    126
    Yes, injection is deprecated, I'd follow their EntityComponentSystemSamples github closely for the latest updates/changes :)
     
  14. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    I got 20fps now.... before using ecs I get 60 - 80fps... for my test scene....
     
  15. psuong

    psuong

    Joined:
    Jun 11, 2014
    Posts:
    126
    Well without posting much information about your systems, it's hard to state what's wrong with it. We can only speculate what could be wrong. If you've got the time and won't mind posting your systems, we can take a look and see what's going on :)
     
  16. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    Code (CSharp):
    1. using System;
    2. using Unity.Entities;
    3. using UnityEngine;
    4.  
    5. [RequireComponent(typeof(CharacterData))]
    6. public class CharacterUserInputData : MonoBehaviour
    7. {
    8.     public bool crouch;
    9.     public bool m_Jump;
    10.     public Vector2 m_Move;
    11. }
    12. public class CharacterUserInput : ComponentSystem
    13. {
    14.     private Transform m_Cam;                  // A reference to the main camera in the scenes transform
    15.     private CharacterUserInputData Data;
    16.     private EntityQuery query;
    17.  
    18.     protected override void OnCreate()
    19.     {
    20.         query = GetEntityQuery(ComponentType.ReadWrite<CharacterUserInputData>());
    21.     }
    22.  
    23.     protected override void OnStartRunning()
    24.     {
    25.         // get the transform of the main camera
    26.         if (Camera.main != null)
    27.         {
    28.             m_Cam = Camera.main.transform;
    29.         }
    30.         else
    31.         {
    32.             Debug.LogWarning(
    33.                 "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.");
    34.             // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
    35.         }
    36.     }
    37.  
    38.     // Fixed update is called in sync with physics
    39.     private void FixedUpdate(Vector3 forward, Vector3 right, bool hasCam, bool walk_Run, bool crouch, bool jump, float h, float v)
    40.     {
    41.         if (!Data.m_Jump)
    42.         {
    43.             Data.m_Jump = jump;
    44.         }
    45.         Data.crouch = crouch;
    46.  
    47.         // calculate move direction to pass to character
    48.         if (hasCam)
    49.         {
    50.             // calculate camera relative direction to move:
    51.             var m_CamForward = Vector3.Scale(forward, new Vector3(1, 0, 1)).normalized;
    52.             Data.m_Move = v * m_CamForward + h * right;
    53.         }
    54.         else
    55.         {
    56.             // we use world-relative directions in the case of no main camera
    57.             Data.m_Move = v * Vector3.forward + h * Vector3.right;
    58.         }
    59. #if !MOBILE_INPUT
    60.         // walk speed multiplier
    61.         if (walk_Run) Data.m_Move *= 0.5f;
    62. #endif
    63.     }
    64.  
    65.     protected override void OnUpdate()
    66.     {
    67.         bool crouch = Input.GetKey(KeyCode.C);
    68.         float h = Input.GetAxis("Horizontal");
    69.         bool jump = Input.GetButtonDown("Jump");
    70.         float v = Input.GetAxis("Vertical");
    71.         bool walk_Run = Input.GetKey(KeyCode.LeftShift);
    72.         bool hasCam = m_Cam != null;
    73.         Vector3 forward = m_Cam.forward;
    74.         Vector3 right = m_Cam.right;
    75.         Entities.With(query).ForEach((CharacterUserInputData data) => {Data = data; FixedUpdate(forward, right, hasCam, walk_Run, crouch,jump,h,v); });
    76.     }
    77. }
    78.  
    79.  
    Code (CSharp):
    1. using Unity.Entities;
    2. using UnityEngine;
    3.  
    4.  
    5. [RequireComponent(typeof(Rigidbody))]
    6. [RequireComponent(typeof(CapsuleCollider))]
    7. [RequireComponent(typeof(Animator))]
    8. public class CharacterData : MonoBehaviour
    9. {
    10.     [SerializeField] public float m_MovingTurnSpeed = 360;
    11.     [SerializeField] public float m_StationaryTurnSpeed = 180;
    12.     [SerializeField] public float m_JumpPower = 12f;
    13.     [Range(1f, 4f)] [SerializeField] public float m_GravityMultiplier = 2f;
    14.     [SerializeField] public float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others
    15.     [SerializeField] public float m_MoveSpeedMultiplier = 1f;
    16.     [SerializeField] public float m_AnimSpeedMultiplier = 1f;
    17.     [SerializeField] public float m_OrigGroundCheckDistance = 0.1f;
    18.     [HideInInspector] public float m_CapsuleHeight;
    19.     [HideInInspector] public Vector3 m_CapsuleCenter;
    20. }
    21.  
    22. public class Character : ComponentSystem
    23. {
    24.     Transform transform;
    25.     Rigidbody m_Rigidbody;
    26.     Animator m_Animator;
    27.     CapsuleCollider m_Capsule;
    28.     CharacterData cData;
    29.     CharacterUserInputData iData;
    30.     bool m_IsGrounded;
    31.     float m_GroundCheckDistance;
    32.     const float k_Half = 0.5f;
    33.     float m_TurnAmount;
    34.     float m_ForwardAmount;
    35.     Vector3 m_GroundNormal;
    36.     bool m_Crouching;
    37.     public EntityQuery query;
    38.     protected override void OnCreate()
    39.     {
    40.         query = GetEntityQuery(ComponentType.ReadWrite<Transform>(), ComponentType.ReadWrite<Rigidbody>(), ComponentType.ReadWrite<Animator>(), ComponentType.ReadWrite<CapsuleCollider>(), ComponentType.ReadWrite<CharacterData>(), ComponentType.ReadWrite<CharacterUserInputData>());
    41.     }
    42.  
    43.  
    44.     public void Move(Vector3 move, bool crouch, bool jump)
    45.     {
    46.  
    47.         // convert the world relative moveInput vector into a local-relative
    48.         // turn amount and forward amount required to head in the desired
    49.         // direction.
    50.         if (move.magnitude > 1f) move.Normalize();
    51.         move = transform.InverseTransformDirection(move);
    52.         CheckGroundStatus();
    53.         move = Vector3.ProjectOnPlane(move, m_GroundNormal);
    54.         m_TurnAmount = Mathf.Atan2(move.x, move.z);
    55.         m_ForwardAmount = move.z;
    56.  
    57.         ApplyExtraTurnRotation();
    58.  
    59.         // control and velocity handling is different when grounded and airborne:
    60.         if (m_IsGrounded)
    61.         {
    62.             HandleGroundedMovement(crouch, jump);
    63.         }
    64.         else
    65.         {
    66.             HandleAirborneMovement();
    67.         }
    68.  
    69.         ScaleCapsuleForCrouching(crouch);
    70.         PreventStandingInLowHeadroom();
    71.  
    72.         // send input and other state parameters to the animator
    73.         UpdateAnimator(move);
    74.     }
    75.  
    76.  
    77.     void ScaleCapsuleForCrouching(bool crouch)
    78.     {
    79.         if (m_IsGrounded && crouch)
    80.         {
    81.             if (m_Crouching) return;
    82.             m_Capsule.height = m_Capsule.height / 2f;
    83.             m_Capsule.center = m_Capsule.center / 2f;
    84.             m_Crouching = true;
    85.         }
    86.         else
    87.         {
    88.             Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
    89.             float crouchRayLength = cData.m_CapsuleHeight - m_Capsule.radius * k_Half;
    90.             if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
    91.             {
    92.                 m_Crouching = true;
    93.                 return;
    94.             }
    95.             m_Capsule.height = cData.m_CapsuleHeight;
    96.             m_Capsule.center = cData.m_CapsuleCenter;
    97.             m_Crouching = false;
    98.         }
    99.     }
    100.  
    101.     void PreventStandingInLowHeadroom()
    102.     {
    103.         // prevent standing up in crouch-only zones
    104.         if (!m_Crouching)
    105.         {
    106.             Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
    107.             float crouchRayLength = cData.m_CapsuleHeight - m_Capsule.radius * k_Half;
    108.             if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
    109.             {
    110.                 m_Crouching = true;
    111.             }
    112.         }
    113.     }
    114.  
    115.  
    116.     void UpdateAnimator(Vector3 move)
    117.     {
    118.         // update the animator parameters
    119.         m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
    120.         m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
    121.         m_Animator.SetBool("Crouch", m_Crouching);
    122.         m_Animator.SetBool("OnGround", m_IsGrounded);
    123.         if (!m_IsGrounded)
    124.         {
    125.             m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
    126.         }
    127.  
    128.         // calculate which leg is behind, so as to leave that leg trailing in the jump animation
    129.         // (This code is reliant on the specific run cycle offset in our animations,
    130.         // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
    131.         float runCycle =
    132.             Mathf.Repeat(
    133.                 m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + cData.m_RunCycleLegOffset, 1);
    134.         float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
    135.         if (m_IsGrounded)
    136.         {
    137.             m_Animator.SetFloat("JumpLeg", jumpLeg);
    138.         }
    139.  
    140.         // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
    141.         // which affects the movement speed because of the root motion.
    142.         if (m_IsGrounded && move.magnitude > 0)
    143.         {
    144.             m_Animator.speed = cData.m_AnimSpeedMultiplier;
    145.         }
    146.         else
    147.         {
    148.             // don't use that while airborne
    149.             m_Animator.speed = 1;
    150.         }
    151.     }
    152.  
    153.  
    154.     void HandleAirborneMovement()
    155.     {
    156.         // apply extra gravity from multiplier:
    157.         Vector3 extraGravityForce = (Physics.gravity * cData.m_GravityMultiplier) - Physics.gravity;
    158.         m_Rigidbody.AddForce(extraGravityForce);
    159.  
    160.         m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? cData.m_OrigGroundCheckDistance : 0.01f;
    161.     }
    162.  
    163.  
    164.     void HandleGroundedMovement(bool crouch, bool jump)
    165.     {
    166.         // check whether conditions are right to allow a jump:
    167.         if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
    168.         {
    169.             // jump!
    170.             m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, cData.m_JumpPower, m_Rigidbody.velocity.z);
    171.             m_IsGrounded = false;
    172.             m_Animator.applyRootMotion = false;
    173.             m_GroundCheckDistance = 0.1f;
    174.         }
    175.     }
    176.  
    177.     void ApplyExtraTurnRotation()
    178.     {
    179.         // help the character turn faster (this is in addition to root rotation in the animation)
    180.         float turnSpeed = Mathf.Lerp(cData.m_StationaryTurnSpeed, cData.m_MovingTurnSpeed, m_ForwardAmount);
    181.         transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
    182.     }
    183.  
    184.  
    185.     public void OnAnimatorMove()
    186.     {
    187.         // we implement this function to override the default root motion.
    188.         // this allows us to modify the positional speed before it's applied.
    189.         if (m_IsGrounded && Time.deltaTime > 0)
    190.         {
    191.             Vector3 v = (m_Animator.deltaPosition * cData.m_MoveSpeedMultiplier) / Time.deltaTime;
    192.  
    193.             // we preserve the existing y part of the current velocity.
    194.             v.y = m_Rigidbody.velocity.y;
    195.             m_Rigidbody.velocity = v;
    196.         }
    197.     }
    198.  
    199.  
    200.     void CheckGroundStatus()
    201.     {
    202.         RaycastHit hitInfo;
    203. #if UNITY_EDITOR
    204.         // helper to visualise the ground check ray in the scene view
    205.         Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
    206. #endif
    207.         // 0.1f is a small offset to start the ray from inside the character
    208.         // it is also good to note that the transform position in the sample assets is at the base of the character
    209.         if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))
    210.         {
    211.             m_GroundNormal = hitInfo.normal;
    212.             m_IsGrounded = true;
    213.             m_Animator.applyRootMotion = true;
    214.         }
    215.         else
    216.         {
    217.             m_IsGrounded = false;
    218.             m_GroundNormal = Vector3.up;
    219.             m_Animator.applyRootMotion = false;
    220.         }
    221.     }
    222.     protected override void OnStartRunning()
    223.     {
    224.         Entities.With(query).ForEach((Entity e, Rigidbody rig, CapsuleCollider cap, CharacterData _cData) =>
    225.         {
    226.             m_Rigidbody = rig;
    227.             m_Capsule = cap;
    228.             cData = _cData;
    229.             cData.m_CapsuleHeight = m_Capsule.height;
    230.             cData.m_CapsuleCenter = m_Capsule.center;
    231.             m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
    232.         });
    233.     }
    234.     protected override void OnUpdate()
    235.     {
    236.         Entities.With(query).ForEach((Entity e, Transform _transform, Animator anim, Rigidbody rig, CapsuleCollider cap, CharacterData cData, CharacterUserInputData data) =>
    237.         {
    238.             m_Animator = anim;
    239.             m_Rigidbody = rig;
    240.             m_Capsule = cap;
    241.             this.cData = cData;
    242.             iData = data;
    243.             transform = _transform;
    244.             m_GroundCheckDistance = cData.m_OrigGroundCheckDistance;
    245.             Move(iData.m_Move, iData.crouch,iData.m_Jump);
    246.         });
    247.     }
    248. }
    Heres the code... Inputs are not read on instance but after a huge delay.... Changed data structs to monobehaviour cause that decreased my fps and editor dosent take inputs......
     
    Last edited: May 11, 2019
  17. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    the foreach is the problem..... Also I cant find a solution too it...
     
  18. starikcetin

    starikcetin

    Joined:
    Dec 7, 2017
    Posts:
    340
    I am trying to prepare a couple of self contained samples for the latest API, but to be honest it is hard to learn at the moment, even for me.
     
  19. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    So there are a lot who is having trouble with new api.... :D
     
  20. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    I wrote a monobehavior to update them manually so they go in a order... but h and v is not updating...
     
  21. psuong

    psuong

    Joined:
    Jun 11, 2014
    Posts:
    126
    Hey so, the first thing you need is to start segmenting and splitting your data. Your character data leans towards an object oriented approach.

    E.g, if you know that a system will need to process animation speed data and you understand that the data type is a float, you can consider creating a struct with float/float2/float3 data.

    Remember that component data lives in chunks, you'll likely not need private "character" references in your ComponentSystem. If you have those private variables related to the character, will your system work for 2 characters? Even if you don't need characters in your game, is it fundamentally viable to add those references in your system even if the data lives in these preallocated chunks?

    You'll also want to split your systems apart. Your component system is doing a tad much. You'll want to have a move system separated from the concept of handling animation too. Similarly, you can apply that to your capsule scale functionality too. A system, should ideally do all the operations which transforms one set of data to another set of data.

    Systems are then scheduled and ordered based on how you need them to run; see the basic example below.

    E.g. CharacterInputSystem -> CharacterGroundedMoveSystem -> CharacterAirbourneMoveSystem -> CharacterCapsuleScaleSystem -> CharacterUpdateAnimationSystem.
     
  22. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    I was thinking of that but how could I split it without creating overheads...
     
  23. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    I did that and now my character runs like flash... But at below 20fps... And is late at updating the inputs....
     
  24. Shuhair_jr

    Shuhair_jr

    Joined:
    Oct 16, 2015
    Posts:
    30
    Im using unity default third person character scripts after converting to ecs....