Search Unity

Enable / Disable renderer's based on Scripts

Discussion in 'Scripting' started by Badass99, Jul 31, 2014.

  1. Badass99

    Badass99

    Joined:
    Jul 28, 2014
    Posts:
    6
    Okay so I have 3 scripts that I want to communicate between each other. The Third script will enable or disable a skinned mesh renderer based on the information from scripts 1 and 2. Script 1 is my Items database. Script 2 is my Inventory. Script 3 is armor equip. Script 2 uses script 1 as an array and if the player picks up an item it'll use the information from script 1 to add it to script 2's inventory. If it's a piece of armor and the character transfer it to the EquipMenu that is inside of Inventory, I want script 3 (armor equip) to turn off my human torso and turn on a piece of armor using renderer.enabled. Here's a piece of script I got to work but it keeps giving me null reference errors.

    Code (csharp):
    1.  
    2. function Update()
    3. {
    4.     if(GameObject.Find("BARB_Male_00").GetComponent("Inventory").EquipMenu[0].Equipped == true)
    5.     Debug.Log("YAY");
    6.     renderer.enabled = false;
    7. }
    8.  
    Thanks for the help!

    PS The Armor script that render's the mesh is on the piece of body. Ex Chest Equip script is on the Torso of my character. I don't know what I have to add to remove the null reference errors.
     
    Last edited: Jul 31, 2014
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Somewhere on that line, one of the things you're trying to "dig into" is null:
    A) Could be the GameObject.Find is returning null
    B) Could be GetComponent is returning null
    C) Could be EquipMenu[0] is null

    Try splitting those into three lines to narrow it down:
    Code (csharp):
    1.  
    2. var barb : GameObject = GameObject.Find("BARB_Male_00");
    3. var inventory : Inventory = barb.GetComponent("Inventory");
    4. if (inventory.EquipMenu[0].Equipped == true) {
    5. //etc
    6.  
    It's also good practice to avoid using GameObject.Find most of the time, and when you use GetComponent, to store the result rather than to search for everything every frame. Both for performance reasons, but also because it helps you avoid and diagnose problems like this one. You can make a public Inventory-type variable, and then drag the Barbarian object into the slot, and it'll link to his Inventory component.
    Code (csharp):
    1.  
    2. public var barbMaleInventory : Inventory;
    3. function Update() {
    4. if (inventory.EquipMenu[0].Equipped == true) {
    5. //whatever
    6. }
    7. }
     
  3. Badass99

    Badass99

    Joined:
    Jul 28, 2014
    Posts:
    6
    Awesome thanks for the advice. I'll give that a shot and see what's happening.