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

Question Composition For Movement

Discussion in 'Scripting' started by yekoba, May 23, 2024.

  1. yekoba

    yekoba

    Joined:
    Apr 26, 2022
    Posts:
    16
    I have move component script but i dont know how to move entities differently. I mean should i create new sub classes of move component? For example I have player and zombie. Their movements are different so i dont know how to do it.
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,594
    I personally favor composition since the whole GameObject/Component structure is a composition design pattern in and of itself.

    If you need to be able to relate certain aspects of the various movement scripts you make, you can create an interface for it.

    Like so:

    Code (csharp):
    1. public interface IMovementScript
    2. {
    3.     GameObject gameObject { get; } //will be implicitly implemented since our scripts are MonoBehaviour
    4.     Transform transform { get; } //also implicitly implemented
    5.     float Speed { get; set; } //say all movement scripts have speed and you want to be able to modify them polymorphically
    6. }
    7.  
    8. public class PlayerMovement : MonoBehaviour, IMovementScript
    9. {
    10.     public float speed;
    11.     float IMovementScript.Speed { get { return speed; } set { speed = value; } }
    12.  
    13.     void Update()
    14.     {
    15.         //update via player inputs
    16.     }
    17. }
    18.  
    19. public class ZombieMovement : MonoBehaviour, IMovementScript
    20. {
    21.     public float speed;
    22.     float IMovementScript.Speed { get { return speed; } set { speed = value; } }
    23.  
    24.     void Update()
    25.     {
    26.         //update via some other means
    27.     }
    28. }
     
    yekoba and spiney199 like this.
  3. yekoba

    yekoba

    Joined:
    Apr 26, 2022
    Posts:
    16
    Oh thank u, should i create new file for each class should i write like u did in same file?
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,594
    They'll have to be in their own file since in Unity any component/MonoBehaviour you want to be able to attach to a GameObject via the editor needs to be in its own file.

    The way unity serializes/associates scripts to be attached in the editor is by the guid stored in the meta file associated with the script file. Go into your folder and you should see (it may be hidden) something like:
    YourScript.cs
    YourScript.cs.meta
     
    spiney199 likes this.