Duplicate script

ok so i build a game and its common when i attach the same script to the same object but on another level i want to change the code abit, there is a way to create kind of “prefab” to a script?
i hate duplicating the script its make alot of mess…
Thanks for helpers.

It’s called inheritance and it goes something like this:

(WARNING: super oversimplified explanation)

public class MyParentClass
{
    protected int aNumber;

    public void DoSomething()
    {
        SetNumber(10);
    }

    protected void SetNumber(int newNumber)
    {
        aNumber = newNumber;
    }
}

public class MyChildClass : MyParentClass
{
    public void DoSomethingElse()
    {
        SetNumber(200);
    }
}

public class MyOtherChildClass : MyParentClass
{
    public void OverNineThousand()
    {
        SetNumber(9000000);
    }
}

In the above very basic example, we have a single MyParentClass script that has a number, a method that sets that number and its own DoSomething method. Then we have 2 other classes that inherit the parent class (“: MyBaseClass”). They have their own methods of doing something, but they all call the same SetNumber method.

Even though the child classes are not defining aNumber and SetNumber, they are both inherited by the parent. Basically you are saying “Make a class with these members, and also whatever members my parent has so I don’t have to write the same thing over and over”.

Note that for the child classes to have access to a parent member, it has to either be protected or public. If its private, you are still inheriting it, but you cannot access them.

Also note that each class has a different method that does something (DoSomething, DoSomethingElse, etc). So to perform each task, you need to call those methods as so:

MyParentClass parent = new MyParentClass();
parent.DoSomething();

MyChildClass child = new MyChildClass();
child.DoSomethingElse();

MyOtherChildClass otherChild = new MyOtherChildClass();
otherChild.OverNineThousand();

You can also use the same method name and override its behavior in the subclass, but I’ll leave you to read the tutorial which explains that.