# Adding a Script onto another Script

**URL:** <https://discussions.unity.com/t/adding-a-script-onto-another-script/851537>\
**Category:** Scripting\
**Tags:** Scripting, Question\
**Created:** [August 9, 2021, 9:09pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537 "2021-08-09T21:09:09Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![docmarine00](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/docmarine00/32/509548_2.png) [@docmarine00](https://discussions.unity.com/u/docmarine00)\
**Post date:** [August 9, 2021, 9:09pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/1 "2021-08-09T21:09:09Z")

</div>

I am working on RPG style combat. I created various classes (scripts) for Characters, Weapons, etc. Im having a problem adding a Weapon onto my Character. For example I have a Character that wants to be able to use a Sword.  
Here is my Weapons script:

```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Weapon : MonoBehaviour
{
    public string weaponName;
    public string description;

    public int baseDamage;

    public bool isRanged;

    // Can this weapon damage a whole party; i.e, bomb
    public bool wholeParty;

    public int speedModifier;
    public int minWeaponSkill;

    public Weapon CreateWeapon(string weaponName, string description, int baseDamage,
        bool isRanged, bool wholeParty, int speedModifier, int minWeaponSkill)
    {
        // Setup weapon properties
        this.weaponName = weaponName;
        this.description = description;
        this.baseDamage = baseDamage;
        this.isRanged = isRanged;
        this.wholeParty = wholeParty;
        this.speedModifier = speedModifier;
        this.minWeaponSkill = minWeaponSkill;

        return this;
    }

```

And here is my Character script:

```csharp
using System;
using UnityEngine;

[System.Serializable]
public class Character : MonoBehaviour
{

    //public GameObject prefab;

    public Weapon currentWeapon;

```

… And so forth . I am able to Instantiate a Character GameObject. What would be the procedure to properly create a new “Sword”, and assign it to a given Characters currentWeapon slot. Im attempting to do this inside another class called CombatHandler. Just looking for a general procedure that would accomplish this .  
Ive attempted a few ways and I get various errors such as a “null reference exception”  
I’m a rookie here, so any help that can be provided would be appreciated. Thank you.

---

<div class="post-metadata">

**Author:** ![Brathnann](https://avatars.discourse-cdn.com/v4/letter/b/e5b9ba/32.png) [@Brathnann](https://discussions.unity.com/u/Brathnann)\
**Post date:** [August 9, 2021, 9:20pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/2 "2021-08-09T21:20:56Z")

</div>

Since weapon is a MonoBehaviour, you could normally just use AddComponent() to add a weapon component to the same GameObject your character script is on and then assign that component to currentWeapon.

However, it’s possible you might just use a scriptableObject or even just a class that holds some data you pull from a text file.

---

<div class="post-metadata">

**Author:** ![Geckoo](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/geckoo/32/899643_2.png) [@Geckoo](https://discussions.unity.com/u/Geckoo)\
**Post date:** [August 9, 2021, 9:47pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/3 "2021-08-09T21:47:00Z")

</div>

Interesting OOP development. It seems to me that you come from C++ or another low level language. If I am wrong, it means that you understand the OOP main idea. You need a reference and it rolls. Take a look at the next example which is easier than yours. At first Object class and another one for reference. On your player there is only the second script - no more ++

```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Weapon // nothing more here
{
    public string weaponName;
    public int damage;
    public int cost;

    public Weapon CreateWeapon(string weaponName, int damage, int cost)
    {
        this.weaponName = weaponName;
        this.damage = damage;
        this.cost = cost;

        return this;
    }
}

```

```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public Weapon newWeapon;

    void Start()
    {
        newWeapon.CreateWeapon("knife", 10, 20);  
        Debug.Log(newWeapon.weaponName + " " + newWeapon.damage + " " + newWeapon.cost);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        { // or you can create another object
            newWeapon.CreateWeapon("saber", 20, 30);
            Debug.Log(newWeapon.weaponName + " " + newWeapon.damage + " " + newWeapon.cost);
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![anon21720413](https://avatars.discourse-cdn.com/v4/letter/a/b5a626/32.png) [@anon21720413](https://discussions.unity.com/u/anon21720413)\
**Post date:** [August 9, 2021, 9:50pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/4 "2021-08-09T21:50:21Z")

</div>

> [@docmarine00](#):
>
> ```csharp
> using UnityEngine;
> using System.Collections.Generic;
> 
> namespace UnityForum
> {
> public enum Weapons { SWORD, AXE, DAGGER, BOW }
> public enum WeaponType { RANGED, MELEE }
> public enum ItemType { WEAPON, ARMOR, }
> 
> public class Player : MonoBehaviour
> {
> public List<PlayerItem> equipedItems;
> private void Start()
> {
> equipedItems = new List<PlayerItem>();
> }
> private void Update()
> {
> if(Input.GetKeyDown(KeyCode.Space))
> {
> EquipItem();
> }
> if(Input.GetKeyDown(KeyCode.I))
> {
> DisplayEquipedItems();
> }
> }
> void EquipItem()
> {
> var newItem = gameObject.AddComponent<PlayerItem>();
> newItem.Init(ItemType.WEAPON, WeaponType.MELEE, Weapons.SWORD);
> equipedItems.Add(newItem);
> }
> void DisplayEquipedItems()
> {
> foreach(PlayerItem item in equipedItems)
> {
> Debug.Log(item.name.ToString());
> }
> }
> }
> public class PlayerItem : MonoBehaviour
> {
> public ItemType itemType;
> public WeaponType weaponType;
> public Weapons equipedWeapon;
> 
> public void Init(ItemType itemType, WeaponType weaponType, Weapons equipedWeapon)
> {
> this.itemType = itemType;
> this.weaponType = weaponType;
> this.equipedWeapon = equipedWeapon;
> }
> }
> }
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![docmarine00](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/docmarine00/32/509548_2.png) [@docmarine00](https://discussions.unity.com/u/docmarine00)\
**Post date:** [August 9, 2021, 10:55pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/5 "2021-08-09T22:55:41Z")

</div>

Thank you all so far for your replies, I’ll consider these options. I started with C++ 20+ years ago in H.S., getting back into programming for enjoyment. For more clarity, I’ll include a section of my CombatHandler, so you can get a sense of what I’m trying to prototype:

```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class CombatHandler : MonoBehaviour
{

    public GameObject pfCharacter;
    public List<GameObject> Characters = new List<GameObject>();

    // Start is called before the first frame update
    void Start()
    {
     
        SetupCombat();
    }

    // Update is called once per frame
    void Update()
    {
        // This Attack() method works. No equipped weapon, just a base damage plus a random number.
        int damage;
        damage = Characters[0].GetComponent<Character>().Attack();

// *** This is what I was trying to do, and it returns an error
      // Weapon sword = sword.CreateWeapon("Long Sword", "A mighty sword", 10, false, false, 0, 0);
      // Characters[0].GetComponent<Character>().currentWeapon = sword;

    }

    void SetupCombat(CombatMode combatMode)
    {
 
        SpawnCharacter();
    }

    private void SpawnCharacter()
    {
       

        //TODO: Iterate though party, spawn each character

        //Instanaiate a new character
        GameObject character = Instantiate(pfCharacter, new Vector3(1, 0, 4), this.transform.rotation) as GameObject;
        character.GetComponent<Character>().Create("Aaragorn", CharacterClass.Knight);
        character.name = "Aragorn";
        Characters.Add(character);

    // This isn't working 
    Weapon sword;
        character.GetComponent<Character>().currentWeapon = sword.CreateWeapon("Sword", "A mighty longsword", 5, false, false, 1, 0);
    }

    private void EndCombat()
    {
        // Cleanup after combat has ended
    }
}

```

---

<div class="post-metadata">

**Author:** ![anon21720413](https://avatars.discourse-cdn.com/v4/letter/a/b5a626/32.png) [@anon21720413](https://discussions.unity.com/u/anon21720413)\
**Post date:** [August 10, 2021, 6:10am UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/6 "2021-08-10T06:10:18Z")

</div>

```csharp
        private void SpawnCharacter()
        {
            //TODO: Iterate though party, spawn each character

            //Instanaiate a new character
            GameObject character = Instantiate(pfCharacter, new Vector3(1, 0, 4), this.transform.rotation) as GameObject;
            character.GetComponent<Character>().Create("Aaragorn", CharacterClass.Knight);
            character.name = "Aragorn";
            Characters.Add(character);

            // This isn't working
            var characterWeapon = character.GetComponent<Character>().currentWeapon;
            characterWeapon = new Weapon("sword","best weapon in the world");

            Debug.Log(characterWeapon.name);
        }
    }
    public class Weapon
    {
    public string name;
    public string desc;
        public Weapon(string name,string desc)
        {
            this.name = name;
            this.desc = desc;
        }
    }

```

I think your code on line 53 and 54 doesnt make sense you create some variable weapon on 53 and then create new variable Weapon as return of your method on line 54, i edited my post above , you can have List of playeritem on player now

---

<div class="post-metadata">

**Author:** ![docmarine00](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/docmarine00/32/509548_2.png) [@docmarine00](https://discussions.unity.com/u/docmarine00)\
**Post date:** [August 10, 2021, 2:47pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/7 "2021-08-10T14:47:01Z")

</div>

> [@MartinMa](#):
>
> ```csharp
> private void SpawnCharacter()
> {
> //TODO: Iterate though party, spawn each character
> 
> //Instanaiate a new character
> GameObject character = Instantiate(pfCharacter, new Vector3(1, 0, 4), this.transform.rotation) as GameObject;
> character.GetComponent<Character>().Create("Aaragorn", CharacterClass.Knight);
> character.name = "Aragorn";
> Characters.Add(character);
> 
> // This isn't working
> var characterWeapon = character.GetComponent<Character>().currentWeapon;
> characterWeapon = new Weapon("sword","best weapon in the world");
> 
> Debug.Log(characterWeapon.name);
> }
> }
> public class Weapon
> {
> public string name;
> public string desc;
> public Weapon(string name,string desc)
> {
> this.name = name;
> this.desc = desc;
> }
> }
> 
> ```
> 
> I think your code on line 53 and 54 doesnt make sense you create some variable weapon on 53 and then create new variable Weapon as return of your method on line 54, i edited my post above , you can have List of playeritem on player now

Thank you, I’m def going to try this out

---

<div class="post-metadata">

**Author:** ![docmarine00](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/docmarine00/32/509548_2.png) [@docmarine00](https://discussions.unity.com/u/docmarine00)\
**Post date:** [August 11, 2021, 4:02pm UTC](https://discussions.unity.com/t/adding-a-script-onto-another-script/851537/8 "2021-08-11T16:02:39Z")

</div>

Thank you all for the advice; I implemented the following way, and called and Attack method that worked!

```csharp
GameObject character = Instantiate(pfCharacter, new Vector3(1, 0, 4), this.transform.rotation) as GameObject;
        character.GetComponent<Character>().Create("Aaragorn", CharacterClass.Knight);
        character.name = "Aragorn";
     

        var characterWeapon = character.GetComponent<Character>().currentWeapon;
       
       characterWeapon.CreateWeapon("Sword", "A mighty longsword", 1, false, false, 1, 0);

```
