Weird problem >.<

Hello,

So, I have writing a script for change weapon when I press a GUI.Button.
The problem is that, when I click on the button, the function for change weapon is executed, but in game, the model of my weapon don’t change. But if I write mannualy in files the same script for load a weapon at the beginning, it’s work ! :o

My GUI script :

var targetObj: Transform;
		 		targetObj = GameObject.Find("Barbare").transform;

		var targetScript: EquipementScript =
targetObj.GetComponent(EquipementScript);
		

 	  		if(GUI.Button (Rect (xNamePerso,yNamePerso +
30,heightNamePerso,widthNamePerso),
"Changer d'arme")){
			targetScript.CalculWeaponActive();
			}

Script for load and calcul weapon :

function CalculWeaponActive(){

		if(WeaponActive == 1){
			WeaponActive = 2; 			}else if(WeaponActive == 2){
			WeaponActive = 3; 			}else if(WeaponActive == 3){
  		WeaponActive = 1; 			}else if(WeaponActive == 0){
  		WeaponActive = 1; 			} }

This script is in the update function of EquipementScript files :

if(WeaponActive == 1){
Sword1.SetActive(true);
Sword2.SetActive(false);
Sword3.SetActive(false); }else
if(WeaponActive == 2){
Sword1.SetActive(false);
Sword2.SetActive(true);
Sword3.SetActive(false); }else
if(WeaponActive == 3){
Sword1.SetActive(false);
Sword2.SetActive(false);
Sword3.SetActive(true); }else
if(WeaponActive == 0){ NoWeapon =
true; Sword1.SetActive(false);
Sword2.SetActive(false);
Sword3.SetActive(false); }

Please help me.

Thanks.

1 Answer

1

Have you confirmed that the parent items are also active? If a parent item is not active then any child element will not be active as a result.

Note that a GameObject may be inactive
because a parent is not active. In
that case, calling SetActive() will
not activate it, but only set the
local state of the GameObject, which
can be checked using
GameObject.activeSelf. This state will
then be used once all parents are
active.

As a side note, why not add your weapons to an array so your solution is scalable?

public GameObject[] weapons = GameObject[3];
int active_weapon = 0;

function next(){
  active_weapon = (active_weapon + 1) % weapons.length;
  foreach(GameObject weapon in weapons){
    weapon.SetActive(false);
  }
  weapons[active_weapon].SetActive(true);
}

Thanks, but I don't understand this part of code : % weapons.length; foreach(GameObject weapon in weapons){ And yes, all of my parent are activated.

–

Where is your code to set Sword1, Sword2, Sword3? How is that handled?

–

Can we assume that the if(GUI.Button(...)) is all being called within a function OnGUI() {...}

–

No, the function OnGUI doesn't contain only that, but this is not the problem because when I try to put a print("Test"); in the CalculWeaponActive, I see in game "Test" when I click on the button, so I think the problem is the SetActive(true)/(false);. A thing to add after a SetActive for reload the model, or something else ...

–

Could you post the full: EquipementScript?

–