Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Unity C# clean,better way to code my feature

Discussion in 'Scripting' started by voobys, Mar 14, 2024.

  1. voobys

    voobys

    Joined:
    Feb 18, 2024
    Posts:
    2
    using System.Collections;
    using System.Collections.Generic;
    using Unity.VisualScripting;
    using UnityEngine;
    using UnityEngine.EventSystems;

    public class ActionWander : FSMAction
    {
    [Header(“Config”)]
    [SerializeField] private float enemyMovementSpeed;


    [SerializeField] private Vector2 moveRange;

    [SerializeField] private EnemyVisual enemyVisual;

    [SerializeField] private LayerMask obstacles;

    private Vector3 movePosition;
    private Rigidbody2D rb;
    private CircleCollider2D circleCollider;

    private RaycastHit2D raycastDownXLeft;
    private RaycastHit2D raycastUpXLeft;
    private RaycastHit2D raycastDownXRight;
    private RaycastHit2D raycastUpXRight;
    private RaycastHit2D raycastLeftYDown;
    private RaycastHit2D raycastRightYDown;
    private RaycastHit2D raycastLeftYUp;
    private RaycastHit2D raycastRightYUp;

    private Vector3 movement;
    private Vector3 moveDirection;

    private float wanderTime;

    Vector3 positionAfterCollision;
    private float timer;

    float randomX;
    float randomY;
    private bool directionLeft;
    private bool collided;
    private bool directionUp;


    private bool isWalking;

    void Awake()
    {

    collided = false;
    rb = GetComponent<Rigidbody2D>();
    circleCollider = GetComponent<CircleCollider2D>();
    isWalking = false;
    }
    void Start()
    {
    GetNewDestination();
    }

    void Update()
    {
    }

    //Reffers to Finite State Machine
    public override void Act()
    {
    timer -= Time.deltaTime;
    moveDirection = (movePosition - transform.position).normalized;
    movement = moveDirection * (enemyMovementSpeed * Time.deltaTime);
    if (Vector3.Distance(transform.position, movePosition) >= 0.2f)
    {
    isWalking = true;
    rb.MovePosition(Vector3.MoveTowards(transform.position, movePosition, 0.1f));

    }
    else
    {
    isWalking = false;
    }

    if (timer <= 0f)
    {
    GetNewDestination();
    timer = Random.Range(1f, 5f);
    }
    enemyVisual.SetWalkingAnimation(isWalking);
    }


    //Getting new random Dest, when the timer is 0
    private void GetNewDestination()
    {
    randomX = Random.Range(-moveRange.x+0.5f, moveRange.x-0.5f);
    if (randomX >= 0)
    {
    randomX += 0.5f;
    }
    else
    {
    randomX -= 0.5f;
    }

    randomY = Random.Range(-moveRange.y + 0.5f, moveRange.y - 0.5f);
    if (randomY >= 0)
    {
    randomY += 0.5f;
    }
    else
    {
    randomY -= 0.5f;
    }

    //if the enemies are hitting the obstacles, they go away from the obcstacle
    //2 raycast per side - because if it is cast just in the middle, sometimes the middle ray is not enough for "if fit in there"
    raycastDownXLeft = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.3f), Vector2.left, 2f, obstacles);
    raycastUpXLeft = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y + 0.3f), Vector2.left, 2f, obstacles);
    raycastDownXRight = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.3f), Vector2.right, 2f, obstacles);
    raycastUpXRight = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y + 0.3f), Vector2.right, 2f, obstacles);
    raycastLeftYUp = Physics2D.Raycast(new Vector2(transform.position.x - 0.3f, transform.position.y), Vector2.up, 2f, obstacles);
    raycastRightYUp = Physics2D.Raycast(new Vector2(transform.position.x + 0.3f, transform.position.y), Vector2.up, 2f, obstacles);
    raycastLeftYDown = Physics2D.Raycast(new Vector2(transform.position.x - 0.3f, transform.position.y), Vector2.down, 2f, obstacles);
    raycastRightYDown = Physics2D.Raycast(new Vector2(transform.position.x + 0.3f, transform.position.y), Vector2.down, 2f, obstacles);



    bool hitDownXLeft = raycastDownXLeft;
    bool hitUpXLeft = raycastUpXLeft;
    if (hitUpXLeft || hitDownXLeft)
    {

    randomX = ChangeXPositionToRight();
    Debug.Log("HITUJE LEFT");
    }


    bool hitDownXRight = raycastDownXRight;
    bool hitUpXRight = raycastUpXRight;
    if (hitDownXRight || hitUpXRight)
    {
    randomX = ChangeXPositionToleft();
    Debug.Log("HITUJE RIGHT");
    }



    bool hitLeftYUp = raycastLeftYUp;
    bool hitRightYUp = raycastRightYUp;
    if (hitLeftYUp || hitRightYUp)
    {
    randomY = ChangeYPositionToDown();
    Debug.Log("HITUJE UP");
    }



    bool hitLeftYDown = raycastLeftYDown;
    bool hitRightYDown = raycastRightYDown;
    if (hitLeftYDown || hitRightYDown)
    {
    randomY = ChangeYPositionToUp();
    Debug.Log("HITUJE DOWN");
    }


    //if obstacle is on LEFT and RIGHT, just move only up and down
    if (hitDownXLeft && hitDownXRight || hitUpXLeft && hitUpXRight)
    {
    randomX = 0;
    }

    //if obstacles is on UP and DOWN, just move only left and right
    if (hitLeftYDown && hitLeftYUp || hitRightYDown && hitRightYUp)
    {
    randomY = 0;
    }



    movePosition = transform.position + new Vector3(randomX, randomY);



    }

    //if obstacles is on left, change to right
    private float ChangeXPositionToRight()
    {
    // Debug.Log("CHANGE TO RIGHT");
    directionLeft = false;
    float changeXRightPosition = Random.Range(0.5f, moveRange.x);
    return changeXRightPosition;


    }

    //if obstacles is on right, change to left
    private float ChangeXPositionToleft()
    {
    // Debug.Log("CHANGE TO LEFT");
    directionLeft = true;
    float changeXLeftPosition = Random.Range(-moveRange.x, -0.5f);
    return changeXLeftPosition;

    }

    //if obstacles is on up, change to down
    private float ChangeYPositionToDown()
    {
    // Debug.Log("CHANGE TO DOWN");
    directionUp = false;
    float changeYDownPosition = Random.Range(-moveRange.y, -0.5f);
    return changeYDownPosition;

    }

    //if obstacles is on down, change to up
    private float ChangeYPositionToUp()
    {
    // Debug.Log("CHANGE TO UP");
    directionUp = true;
    float changeYUpPosition = Random.Range(0.5f, moveRange.y);
    return changeYUpPosition;

    }

    private void OnDrawGizmosSelected()
    {
    if (moveRange != Vector2.zero)
    {
    Gizmos.color = Color.black;
    Gizmos.DrawWireCube(transform.position, moveRange * 2f);
    Gizmos.DrawLine(transform.position, movePosition);
    }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
    moveDirection = transform.position;
    isWalking = false;


    }

    }

    my answer is - How it could be in better, clean and more professional way?
    Another thing, I am trying 2 day make enemy stop moving when they hit the obstacle, because now they are stucking and try to move into the obstacles…
    I tried make rb.MovePosition, didnt work, I tried make if finalDestination is in obstacle, it doesnt run. But it would be soo hard because I have to make refenreces of every object? I can do the animation - isWalking true/false. and if they hit the obstacle, they change the animation… But I cant figure out how to stop moving. If I use collidersEnter, when the enemy hit the obstacle, it will always oncollided, so it never move again… Thank you:)
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,694
  3. voobys

    voobys

    Joined:
    Feb 18, 2024
    Posts:
    2
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using Unity.VisualScripting;
    4. using UnityEngine;
    5. using UnityEngine.EventSystems;
    6.  
    7. public class ActionWander : FSMAction
    8. {
    9. [Header(“Config”)]
    10. [SerializeField] private float enemyMovementSpeed;
    11.  
    12.  
    13. [SerializeField] private Vector2 moveRange;
    14.  
    15. [SerializeField] private EnemyVisual enemyVisual;
    16.  
    17. [SerializeField] private LayerMask obstacles;
    18.  
    19. private Vector3 movePosition;
    20. private Rigidbody2D rb;
    21. private CircleCollider2D circleCollider;
    22.  
    23. private RaycastHit2D raycastDownXLeft;
    24. private RaycastHit2D raycastUpXLeft;
    25. private RaycastHit2D raycastDownXRight;
    26. private RaycastHit2D raycastUpXRight;
    27. private RaycastHit2D raycastLeftYDown;
    28. private RaycastHit2D raycastRightYDown;
    29. private RaycastHit2D raycastLeftYUp;
    30. private RaycastHit2D raycastRightYUp;
    31.  
    32. private Vector3 movement;
    33. private Vector3 moveDirection;
    34.  
    35. private float wanderTime;
    36.  
    37. Vector3 positionAfterCollision;
    38. private float timer;
    39.  
    40. float randomX;
    41. float randomY;
    42. private bool directionLeft;
    43. private bool collided;
    44. private bool directionUp;
    45.  
    46.  
    47. private bool isWalking;
    48.  
    49. void Awake()
    50. {
    51.  
    52. collided = false;
    53. rb = GetComponent<Rigidbody2D>();
    54. circleCollider = GetComponent<CircleCollider2D>();
    55. isWalking = false;
    56. }
    57. void Start()
    58. {
    59. GetNewDestination();
    60. }
    61.  
    62. void Update()
    63. {
    64. }
    65.  
    66. //Reffers to Finite State Machine
    67. public override void Act()
    68. {
    69. timer -= Time.deltaTime;
    70. moveDirection = (movePosition - transform.position).normalized;
    71. movement = moveDirection * (enemyMovementSpeed * Time.deltaTime);
    72. if (Vector3.Distance(transform.position, movePosition) >= 0.2f)
    73. {
    74. isWalking = true;
    75. rb.MovePosition(Vector3.MoveTowards(transform.position, movePosition, 0.1f));
    76.  
    77. }
    78. else
    79. {
    80. isWalking = false;
    81. }
    82.  
    83. if (timer <= 0f)
    84. {
    85. GetNewDestination();
    86. timer = Random.Range(1f, 5f);
    87. }
    88. enemyVisual.SetWalkingAnimation(isWalking);
    89. }
    90.  
    91.  
    92. //Getting new random Dest, when the timer is 0
    93. private void GetNewDestination()
    94. {
    95. randomX = Random.Range(-moveRange.x+0.5f, moveRange.x-0.5f);
    96. if (randomX >= 0)
    97. {
    98. randomX += 0.5f;
    99. }
    100. else
    101. {
    102. randomX -= 0.5f;
    103. }
    104.  
    105. randomY = Random.Range(-moveRange.y + 0.5f, moveRange.y - 0.5f);
    106. if (randomY >= 0)
    107. {
    108. randomY += 0.5f;
    109. }
    110. else
    111. {
    112. randomY -= 0.5f;
    113. }
    114.  
    115. //if the enemies are hitting the obstacles, they go away from the obcstacle
    116. //2 raycast per side - because if it is cast just in the middle, sometimes the middle ray is not enough for "if fit in there"
    117. raycastDownXLeft = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.3f), Vector2.left, 2f, obstacles);
    118. raycastUpXLeft = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y + 0.3f), Vector2.left, 2f, obstacles);
    119. raycastDownXRight = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.3f), Vector2.right, 2f, obstacles);
    120. raycastUpXRight = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y + 0.3f), Vector2.right, 2f, obstacles);
    121. raycastLeftYUp = Physics2D.Raycast(new Vector2(transform.position.x - 0.3f, transform.position.y), Vector2.up, 2f, obstacles);
    122. raycastRightYUp = Physics2D.Raycast(new Vector2(transform.position.x + 0.3f, transform.position.y), Vector2.up, 2f, obstacles);
    123. raycastLeftYDown = Physics2D.Raycast(new Vector2(transform.position.x - 0.3f, transform.position.y), Vector2.down, 2f, obstacles);
    124. raycastRightYDown = Physics2D.Raycast(new Vector2(transform.position.x + 0.3f, transform.position.y), Vector2.down, 2f, obstacles);
    125.  
    126.  
    127.  
    128. bool hitDownXLeft = raycastDownXLeft;
    129. bool hitUpXLeft = raycastUpXLeft;
    130. if (hitUpXLeft || hitDownXLeft)
    131. {
    132.  
    133. randomX = ChangeXPositionToRight();
    134. Debug.Log("HITUJE LEFT");
    135. }
    136.  
    137.  
    138. bool hitDownXRight = raycastDownXRight;
    139. bool hitUpXRight = raycastUpXRight;
    140. if (hitDownXRight || hitUpXRight)
    141. {
    142. randomX = ChangeXPositionToleft();
    143. Debug.Log("HITUJE RIGHT");
    144. }
    145.  
    146.  
    147.  
    148. bool hitLeftYUp = raycastLeftYUp;
    149. bool hitRightYUp = raycastRightYUp;
    150. if (hitLeftYUp || hitRightYUp)
    151. {
    152. randomY = ChangeYPositionToDown();
    153. Debug.Log("HITUJE UP");
    154. }
    155.  
    156.  
    157.  
    158. bool hitLeftYDown = raycastLeftYDown;
    159. bool hitRightYDown = raycastRightYDown;
    160. if (hitLeftYDown || hitRightYDown)
    161. {
    162. randomY = ChangeYPositionToUp();
    163. Debug.Log("HITUJE DOWN");
    164. }
    165.  
    166.  
    167. //if obstacle is on LEFT and RIGHT, just move only up and down
    168. if (hitDownXLeft && hitDownXRight || hitUpXLeft && hitUpXRight)
    169. {
    170. randomX = 0;
    171. }
    172.  
    173. //if obstacles is on UP and DOWN, just move only left and right
    174. if (hitLeftYDown && hitLeftYUp || hitRightYDown && hitRightYUp)
    175. {
    176. randomY = 0;
    177. }
    178.  
    179.  
    180.  
    181. movePosition = transform.position + new Vector3(randomX, randomY);
    182.  
    183.  
    184.  
    185. }
    186.  
    187. //if obstacles is on left, change to right
    188. private float ChangeXPositionToRight()
    189. {
    190. // Debug.Log("CHANGE TO RIGHT");
    191. directionLeft = false;
    192. float changeXRightPosition = Random.Range(0.5f, moveRange.x);
    193. return changeXRightPosition;
    194.  
    195.  
    196. }
    197.  
    198. //if obstacles is on right, change to left
    199. private float ChangeXPositionToleft()
    200. {
    201. // Debug.Log("CHANGE TO LEFT");
    202. directionLeft = true;
    203. float changeXLeftPosition = Random.Range(-moveRange.x, -0.5f);
    204. return changeXLeftPosition;
    205.  
    206. }
    207.  
    208. //if obstacles is on up, change to down
    209. private float ChangeYPositionToDown()
    210. {
    211. // Debug.Log("CHANGE TO DOWN");
    212. directionUp = false;
    213. float changeYDownPosition = Random.Range(-moveRange.y, -0.5f);
    214. return changeYDownPosition;
    215.  
    216. }
    217.  
    218. //if obstacles is on down, change to up
    219. private float ChangeYPositionToUp()
    220. {
    221. // Debug.Log("CHANGE TO UP");
    222. directionUp = true;
    223. float changeYUpPosition = Random.Range(0.5f, moveRange.y);
    224. return changeYUpPosition;
    225.  
    226. }
    227.  
    228. private void OnDrawGizmosSelected()
    229. {
    230. if (moveRange != Vector2.zero)
    231. {
    232. Gizmos.color = Color.black;
    233. Gizmos.DrawWireCube(transform.position, moveRange * 2f);
    234. Gizmos.DrawLine(transform.position, movePosition);
    235. }
    236. }
    237.  
    238. private void OnCollisionEnter2D(Collision2D collision)
    239. {
    240. moveDirection = transform.position;
    241. isWalking = false;
    242.  
    243.  
    244. }
    245.  
    246. }
    247.  
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,374
    Rather than posting walls of code and paragraphs of questions and "better way to code my feature," try this approach:

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?
     
    dstears and samana1407 like this.