Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to create prefab variants with different behaviors without reassignment

Discussion in 'Prefabs' started by igaguri132, May 9, 2023.

  1. igaguri132

    igaguri132

    Joined:
    Apr 20, 2023
    Posts:
    5
    I have a base prefab and a parent class for characters.
    Code (CSharp):
    1. public class CharacterParent : MonoBehaviour
    2. {
    3.     public Rigidbody2D rigid2D;
    4. }
    I want to create two prefab variant with different behavior and class.
    For example,
    Code (CSharp):
    1. public class CharacterChild1 : CharacterParent
    2. {
    3.     void Update() {transform.position.x += 5f;}
    4. }
    Code (CSharp):
    1. public class CharacterChild2 : CharacterParent
    2. {
    3.     void Update() {rigid2D.rotation += 10f;}
    4. }
    I currently add a new script for each variant, but it's tedious to reassign variables like rigid2D.
    Is there easier way to do this?
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,456
    Get them in Start() or Awake() and make them private.
    You can use RequireComponent to force a component on the same object as the script so it's always there
     
  3. igaguri132

    igaguri132

    Joined:
    Apr 20, 2023
    Posts:
    5
    What I wanted to do was something like automatically generating child classes, but it seems that Start/Awake method is sufficient. And I didn't know about RequireComponent, so I'll try to use it too.
    Thank you very much.
     
    DevDunk likes this.