Unity script crashes editor - c#

Here is my code:
void Update()
{
if (shipController.Mode == ShipController.ShipMode.Build)
{
var mouseInWorld = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
Debug.Log(mouseInWorld);
var mousePos = new Vector2(mouseInWorld.x, mouseInWorld.y);
var currentPos = new Vector2(transform.position.x, transform.position.y);
var posToTarget = mousePos - currentPos;
var oldPosToTarget = posToTarget;
var oldPos = currentPos;
var shotPastTargetOrExact = false;
var iter = 0;
while (!shotPastTargetOrExact)
{
iter++;
Debug.Log(iter);
oldPos = currentPos;
oldPosToTarget = posToTarget;
if (posToTarget == Vector2.zero) shotPastTargetOrExact = true;
if (Mathf.Abs(posToTarget.x) >= Mathf.Abs(posToTarget.y))
{
if (posToTarget.x > 0) currentPos = new Vector2(currentPos.x += blockdistance, currentPos.y);
else currentPos = new Vector2(currentPos.x -= blockdistance, currentPos.y);
}
else
{
if (posToTarget.y > 0) currentPos = new Vector2(currentPos.x, currentPos.y += blockdistance);
else currentPos = new Vector2(currentPos.x, currentPos.y -= blockdistance);
}
posToTarget = mousePos - currentPos;
if (posToTarget.sqrMagnitude > oldPosToTarget.sqrMagnitude)
{
shotPastTargetOrExact = true;
currentPos = oldPos;
}
}
if (currentSlot != null && currentSlot.CurrentItemDragAndDrop != null && currentSlot.CurrentItemDragAndDrop.Item != null)
{
var item = currentSlot.CurrentItemDragAndDrop.Item;
if (currentPlacementBlock == null)
{
currentPlacementBlock = Instantiate(item.BlockPrefab);
}
currentPlacementBlock.transform.localPosition = currentPos;
currentPlacementBlock.transform.rotation = shipController.transform.rotation;
}
else if (currentPlacementBlock != null)
{
Destroy(currentPlacementBlock);
currentPlacementBlock = null;
}
}
}
It crashes when I try to stop the game with the play button in the editor. It has also crashed when starting build mode (see shipController.Mode)
The script works as intended but crashes when stopping the game.
I loged the iterations to try and see if it was looping forever but it doesnt seem to be that as it always comes out with a small iter number in the console

I fixed it by checking if the mouse was in the window before going ahead and performing the rest of the update
bool IsMouseOverGameWindow { get { var mousePosition = Mouse.current.position.ReadValue(); return !(0 > mousePosition.x || 0 > mousePosition.y || Screen.width < mousePosition.x || Screen.height < mousePosition.y); } }

Related

Random Bug in Unity2D

I've been working on a project for the GMTK 2022 Game Jam recently, and I ran into a very strange problem. I have a dash that starts when you are moving and press space. It moves you in the direction of your velocity, then for a short time lets you move very quickly. It works perfectly fine in all cases, unless the direction you are moving is up and to the left, in which case, the if statement strangely won't trigger. I'm sure this is something idiotic, but I've been troubleshooting it for the last hour and it's been driving me insane.
// Update is called once per frame
void Update()
{
playerInputh = 0;
playerInputv = 0;
if (Input.GetKey("right"))
{
playerInputh = 1;
}
if (Input.GetKey("left"))
{
playerInputh = -1;
}
if (Input.GetKey("right") && Input.GetKey("left"))
{
playerInputh = 0;
}
if (Input.GetKey("up"))
{
playerInputv = 1;
}
if (Input.GetKey("down"))
{
playerInputv = -1;
}
if (Input.GetKey("up") && Input.GetKey("down"))
{
playerInputv = 0;
}
Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
//This is the dash that isn't working:
if ((Input.GetKeyDown(/*"right shift"*/"space")) && (playerInputh != 0 || playerInputv != 0))
{
Debug.Log("Dash");
//Vector2 transform2dposition = new Vector2(transform.position.x, transform.position.y);
m_Rigidbody.AddForce((m_Rigidbody.velocity) * 500f);
wJumpTimer = airControlAfterJump;
speed = maxSpeed*3.5f;
StartCoroutine(Roll());
}
}
void FixedUpdate()
{
//no moving while jumping!!!
if (wJumpTimer > 0)
{
wJumpTimer -= 1;
}
else
{
wJumpTimer = 0;
}
//move
if (playerInputh != 0 && playerInputv != 0) //make diagonals no super sayan
{
playerInputh *= moveLimiter;
playerInputv *= moveLimiter;
one_h = playerInputh;//futureproof
one_v = playerInputv;
}
if ((playerInputh != 0 || playerInputv != 0) && speed < maxSpeed) //are we hitting the move buttons??
{
speed += acceleration;//accelerate
one_h = playerInputh;//futureproof
one_v = playerInputv;
}
else
{
if (speed > 0f) //are we getting off the ride
{
speed -= deceleration; //decelerate
}
else
{
speed = 0f; //no funny buisness
}
}
m_Rigidbody.velocity = new Vector2(one_h * speed, one_v * speed); //actually move
}
void SetFace(int diceNumb)
{
rndr.sprite = sprites[diceNumb];
}
IEnumerator Roll()
{
Random diceNumb = new Random();
rndr.sprite = sprites[diceNumb.Next(0,5)];
yield return new WaitForSeconds(0.125f);
rndr.sprite = sprites[diceNumb.Next(0, 5)];
yield return new WaitForSeconds(0.125f);
rndr.sprite = sprites[diceNumb.Next(0, 5)];
yield return new WaitForSeconds(0.125f);
rndr.sprite = sprites[diceNumb.Next(0, 5)];
yield return new WaitForSeconds(0.125f);
var newValue = diceNumb.Next(0, 5);
FaceValue = newValue + 1;
rndr.sprite = sprites[newValue];
}
How are your inputs setup? I am suspecting you have one key bound to multiple actions, like one key is set up as primary for an action and alternate for another action.
Personally I'd also stop using the assignment operators and increment instead. Instead of
playerInputh = 0;
if (Input.GetKey("right"))
{
playerInputh = 1;
}
if (Input.GetKey("left"))
{
playerInputh = -1;
}
if (Input.GetKey("right") && Input.GetKey("left"))
{
playerInputh = 0;
}
you can do
playerInputv = 0;
if (Input.GetKey("right"))
{
playerInputh += 1;
}
if (Input.GetKey("left"))
{
playerInputh += -1;
}
Net result is the same here - if you push both keys the result sums to zero, but the code is easier to read (IMO).
When you check things for key bindings also check alternates for space, because that's another one of the triggers you need to dash.

Spine2d legs adjustments to ground

In project I'm currently working on I need to adjust legs position to ground when character stands on a ramp, to avoid look like any of his legs floating above the ground. I think i need to do it somewhere in this method, but I can't figure out how.
public void SetCharacterState(string state)
{
currentState = state;
if (state.Equals("Idle") && once != 0)
{
SetAnimation(idle, true, 1f);
print("Correcting legs position");
once = 0;
}
if (state.Equals("Run") && once != 1)
{
SetAnimation(run, true, 1f);
once = 1;
}
if (state.Equals("jumpFrom_Idle") && once != 2)
{
SetAnimation(jumpFrom_Idle, false, 1f);
StartCoroutine(IE_jump());
canAnimationChange = false;
once = 2;
}
if (state.Equals("jumpFrom_Run") && once != 3)
{
SetAnimation(jumpFrom_Run, false, 1f);
StartCoroutine(IE_jump());
canAnimationChange = false;
once = 3;
}
if (state.Equals("freeFall") && once != 4)
{
SetAnimation(freeFall, true, 1f);
once = 4;
}
if (state.Equals("freeFall_Land") && once != 5)
{
SetAnimation(freeFall_Land, false, 1f);
StartCoroutine(IE_freeFall_Land());
controller.canJump = false;
canAnimationChange = false;
once = 5;
}
}
Any suggestions?

How to prevent drag and drop if the node is not null [C#]

I have a problem with drag and drop on game. I want to block user if he is dragging the object from down to up in case they have sticks in same angles. if they dont so it is ok. But if they have even one stick in same direction so stick should go back to down to first position.
I am lost a bit. Can you help please :)
here is the code where I drag and drop also rotation...
Here on the pic generated stick group can fit only 1. and 3. places.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputController : MonoBehaviour
{
float clickTime;
RaycastHit2D rayhit;
float smallestDistance = 1.5f;
int smallestId = 1;
public Transform[] nodes;
public LayerMask selectableObjLayerMask;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
clickTime = Time.time;
rayhit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, selectableObjLayerMask);
}
else if (Input.GetMouseButtonUp(0))
{
if (rayhit)
{
if (Time.time - clickTime < .2f)
{
Node node = rayhit.transform.GetComponent<Node>();
if (node != null)
{
for (int i = 0; i < node.sticks.Count; i++)
{
Vector3 newAngles = new Vector3(0, 0, (node.sticks[i].transform.localEulerAngles.z - 45));
newAngles.z = newAngles.z < 0 ? newAngles.z + 180 : newAngles.z;
newAngles.z = newAngles.z >180 ? newAngles.z - 180 : newAngles.z;
node.sticks[i].transform.localEulerAngles = newAngles;
node.sticks[i].degree = (int)newAngles.z;
Debug.Log(i + " = " + node.sticks[i].degree);
}
}
}
else
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode.isMoved == false)
{
smallestId = 0;
smallestDistance = 999;
for (int i = 0; i < nodes.Length; i++)
{
float distance = Vector2.Distance(rayhit.transform.position, nodes[i].transform.position);
if (smallestDistance > distance)
{
smallestDistance = distance;
smallestId = i;
Debug.Log("Obje : " + currNode);
}
}
rayhit.transform.position = nodes[smallestId].transform.position;
if (rayhit.transform.parent != nodes[smallestId].transform)
{
if (nodes[smallestId].transform.childCount > 0 && nodes[smallestId].transform != rayhit.transform.parent)
{
if (currNode != null)
{
for (int i = 0; i < currNode.sticks.Count; i++)
{
nodes[smallestId].transform.GetChild(0).GetComponent<Node>().sticks.Add(currNode.sticks[i]);
currNode.sticks[i].transform.SetParent(nodes[smallestId].transform.GetChild(0));
}
Destroy(rayhit.transform.gameObject);
}
}
else
{
if (currNode != null)
{
currNode.isMoved = true;
}
rayhit.transform.SetParent(nodes[smallestId].transform);
}
}
}
}
}
rayhit = new RaycastHit2D();
}
else if (Input.GetMouseButton(0))
{
if(rayhit.transform != null)
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode != null)
if (currNode.isMoved == false)
{
if (Time.time - clickTime >= 0.2f)
{
Vector2 newPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rayhit.transform.position = newPos;
}
}
}
}
}
}

How to save a list of items in Unity?

I don't know how to save a List<T> of items I have and the inventory script and the database items script. I want to save the items that I have in my inventory but I don't know how. I try to create a class and make an Update() function but id doesn't work. It gives me an error
inventory<item> can't be deserialized
Can you help me please how should I save the items?
Here is the script o the player data that contains the save/load functions.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
public class PlayerData : MonoBehaviour {
public int HP,MP,HPMAX,MPMAX,STR,DEF,EXP,LVL;
public Text HPtext,MPtext,STRtext,DEFtext,LVLtext,amountTxt;
public static PlayerData Pdata;
public GameObject player;
public int amount = 20;
public bool UseKey;
public bool poisened;
public float counter = 5;
//==============================================================
public List<Item> Inventory = new List<Item> ();
//==============================================================
public float x,y ;
inventoryTest inv;
void Awake()
{
if(Pdata == null)
{
DontDestroyOnLoad(gameObject);
Pdata = this;
}
else if(Pdata != this)
{
Destroy(gameObject);
}
}
void Start()
{
inv = GameObject.FindWithTag("Player").GetComponent<inventoryTest>();
HP = 20;
MP = 5;
HPMAX = 20;
MPMAX = 5;
STR = 8;
DEF = 8;
EXP = 0;
LVL = 1;
}
void Update()
{
//==========================================
Inventory = inv.Inventory;
//==========================================
amountTxt.text = ""+amount;
HPtext.text = ""+HP;
MPtext.text = ""+MP;
STRtext.text = ""+STR;
DEFtext.text = ""+DEF;
LVLtext.text = ""+LVL;
x = player.transform.position.x;
y = player.transform.position.y;
if(HP > HPMAX){
HP = HPMAX;
}
if(MP > MPMAX){
MP = MPMAX;
}
if(MP <= 0){
MP = 0;
}
if(HP <= 0){
HP = 0;
}
if(amount <= 0){
amount = 0;
}
if(amount >= 99){
amount = 99;
}
if(EXP == 100){
EXP = 0;
LVL++;
STR++;
DEF++;
HPMAX += 10;
MPMAX += 5;
}
if(LVL == 99){
LVL = 99;
}
}
void FixedUpdate(){
if(poisened){
counter -= Time.deltaTime;
if(counter < 0f){
HP -= 1;
counter = 5;
}
}
}
public void Save(){
BinaryFormatter BF = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/S_F.dat" );
playerDataClass data = new playerDataClass();
data.HP = HPMAX;
data.MP = MPMAX;
data.STR = STR;
data.DEF = DEF;
data.EXP = EXP;
data.LVL = LVL;
data.y = y;
data.x = x;
//====================================
data.Inventory = Inventory;
//====================================
BF.Serialize(file,data);
file.Close();
}
public void Load(){
if(File.Exists(Application.persistentDataPath + "/S_F.dat")){
BinaryFormatter BF = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/S_F.dat", FileMode.Open);
playerDataClass data = (playerDataClass) BF.Deserialize(file);
file.Close();
HPMAX = data.HPMAX;
MPMAX = data.MPMAX;
HP = data.HP;
MP = data.MP;
STR = data.STR;
DEF = data.DEF;
EXP = data.EXP;
LVL = data.LVL;
x = data.x;
y = data.y;
player.transform.position= new Vector2(x,y);
}
}
}
[Serializable]
public class playerDataClass
{
public int HPMAX,MPMAX,HP,MP,STR,DEF,EXP,LVL;
public float x,y ;
//=======================================================
public List<Item> Inventory = new List<Item> ();
//=======================================================
}
Edit here is he Inventory Script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class inventoryTest : MonoBehaviour {
public Transform panel,MenuPosition,gPanelPosition;
public List<Item> Inventory = new List<Item> ();
public ItemDatabase data;
public Text testText,saveTextl,USEtext,EQUIPtext;
PlayerData Playerdata;
PlayerControl contol;
public Color saveColor;
public bool Eaquiped;
int GeneralMenu = 2;
int optionMenu = 2;
int Index3 = 0;
int Index2 = 0;
int Index = 0;
public float Yoffset;
public Image iconGeneral,iconMini,icon;
public GameObject saveMessage,ave,arrowAmount,gPanel,itemOption,camerA,Menu;
public bool A,B,moveup,movedown,SaveOptionAvalable,openOption,gOption,t,pressed,faceDoor;
void Start(){
contol = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerControl> ();
Playerdata = GameObject.FindGameObjectWithTag ("Playerdata").GetComponent<PlayerData> ();
data = GameObject.FindGameObjectWithTag ("database").GetComponent<ItemDatabase> ();
camerA = GameObject.FindWithTag("MainCamera");
Color colorT = saveColor;
colorT.a = 0.1f;
saveTextl.color = colorT;
gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
itemOption.SetActive(false);
saveMessage.SetActive(false);
}
void Update (){
t = true;
if(SaveOptionAvalable){
Color colorT = saveColor;
colorT.a = 1f;
saveTextl.color = colorT;
}else if(!SaveOptionAvalable){
Color colorT = saveColor;
colorT.a = 0.1f;
saveTextl.color = colorT;
}
//====== Menu DESPLAY ==========================================================================================================================
//==for toch cotrole====================================================================================
if (B && !pressed) {
pressed = true;
Menu.transform.position = new Vector2(camerA.transform.position.x,camerA.transform.position.y);
Time.timeScale = 0;
arrowAmount.SetActive(false);
B = !B;
}else if (B && pressed && !openOption && !gOption && !SaveOptionAvalable) {
Time.timeScale = 1;
pressed = !pressed;
Menu.transform.position = new Vector2(MenuPosition.transform.position.x,MenuPosition.transform.position.y);
if(contol.equipbow == true)
{
arrowAmount.SetActive(true);
}
B = !B;
}
else if (B && pressed && openOption){
openOption = !openOption;
itemOption.SetActive(false);
Color colorT = saveColor;
colorT.a = 1f;
USEtext.color = colorT;
EQUIPtext.color = colorT;
B = !B;
}
//====BACK TO GENERAL MENU===============================================================================================================
//=====FOR TOCH CONTROL==============================================================================
if(B && pressed && gOption) {
gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
gOption = !gOption;
if(contol.inSaveErea == true){
SaveOptionAvalable = true;
}
else if (contol.inSaveErea == false){
SaveOptionAvalable = false;
}
B = !B;
}
if( A && pressed && !gOption) {
if(Index3 == 0){
gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x,gPanelPosition.transform.position.y);
gOption = true;
Debug.Log(gOption);
SaveOptionAvalable = false;
A =!A;
}
if(Index3 == 1 && SaveOptionAvalable && !gOption){
saveMessage.SetActive(true);
Debug.Log(SaveOptionAvalable);
gOption = true;
A =!A;
}
}
//=====================================================================================================
//==== KEYBOARD CONTROL================================================================================
// if(Input.GetKeyDown (KeyCode.B)&& pressed && gOption ){
// gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
// gOption = !gOption;
// }
// if(Input.GetKeyDown(KeyCode.A) && pressed && !gOption){
// if(Index3 == 0){
// gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x,gPanelPosition.transform.position.y);
// gOption = true;
// Debug.Log(gOption);
// return;
// }
// if(Index3 == 1 && !SaveOptionAvalable){
// }
// if(Index3 == 2){
// }
// }
//=======================================================================================================================================
//===SAVE BITTON AND SAVE MESSAGE========================================================================================================
//====TOUCH CONTROL===================================================================================================
if(A && pressed && SaveOptionAvalable)
{
saveMessage.SetActive(false);
Playerdata.Save();
Debug.Log("SAVED");
SaveOptionAvalable = !SaveOptionAvalable;
gOption = !gOption;
A = !A;
}
if(B && pressed && SaveOptionAvalable)
{
saveMessage.SetActive(false);
SaveOptionAvalable = true;
SaveOptionAvalable = !SaveOptionAvalable;
Debug.Log("CANCELED");
B = !B;
}
//===KEYBOARD CONTROL==================================================================================================
//=============================================================================================================================
//===UP/DOWN NAVIGATION MENU===================================================================================================
//===TOUCH CONTROL==============================================================
if(movedown && pressed && !gOption && !openOption ){
movedown = !movedown;
if(Index3 < GeneralMenu -1){
Index3++;
Vector2 position = iconGeneral.transform.position;
position.y -= Yoffset;
iconGeneral.transform.position = position;
return;
}
}
if(moveup && pressed && !gOption && !openOption){
moveup = !moveup;
if(Index3 > 0){
Index3--;
Vector2 position = iconGeneral.transform.position;
position.y += Yoffset;
iconGeneral.transform.position = position;
return;
}
}
//=======INVENTORY : Selectig Item With Up and Down Arrows and pressing A to Use and B to Cancel ============================================================================================================================
for(int i = 0 ; i < Inventory.Count; i++){
//===TOUCH CONTROL========================================================================================
if(movedown && pressed){
movedown = !movedown;
if(Index < Inventory.Count -1 && !openOption ){
Index++;
Vector2 position = icon.transform.position;
position.y -= Yoffset;
icon.transform.position = position;
return;
}if(Index2 < optionMenu -1 && openOption){
Index2++;
Vector2 position = iconMini.transform.position;
position.y -= Yoffset;
iconMini.transform.position = position;
return;
}
}
if(moveup && pressed){
moveup = !moveup;
if(Index > 0 && !openOption ){
Index -- ;
Vector2 position = icon.transform.position;
position.y += Yoffset;
icon.transform.position = position;
return;
}if(Index2 > 0 && openOption){
Index2--;
Vector2 position = iconMini.transform.position;
position.y += Yoffset;
iconMini.transform.position = position;
return;
}
}
//===============================================================================================================
//======= USE/EQUIPE MENU ===================================================================================================
//===TOUCH CONTROL===============================================================================================
if(A && pressed && !openOption && gOption && !SaveOptionAvalable){
openOption = true;
itemOption.SetActive(true);
A = !A;
}
if(A && openOption){
openOption = !openOption;
//===== IF PRESS USE TOUCH CONTROL=================================================================================================
if(Index2 == 1)
{
if(Index == i){
if(Inventory[i].ItemId == 5 && contol.equipSword == true && contol.equipbow == false){
contol.equipSword = false;
contol.equipbow = true;
t = false;
var ttt = GameObject.Find("sword").GetComponent<Text>();
ttt.text = "sword" + "";
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
if(Inventory[i].ItemId == 4 && contol.equipSword == false && contol.equipbow == true){
contol.equipSword = true;
contol.equipbow = false;
t = false;
var ttt = GameObject.Find("bow").GetComponent<Text>();
ttt.text = "bow" + "";
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
if(Inventory[i].ItemId == 4 && contol.equipSword == false)
{
contol.equipSword = true;
contol.equipbow = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
else if(Inventory[i].ItemId == 4 && contol.equipSword == true){
contol.equipSword = false;
contol.equipbow = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname;
A =!A;
}
if(Inventory[i].ItemId == 5 && contol.equipbow == false)
{
contol.equipbow = true;
contol.equipSword = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + " <E>";
A =!A;
}
else if(Inventory[i].ItemId == 5 && contol.equipbow == true){
contol.equipbow = false;
contol.equipSword = false;
t = false;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname;
A =!A;
}
if(Inventory[i].ItemId == 0)
{
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 1)
{
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 2)
{
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 3)
{
if(!faceDoor){
Color colorT = saveColor;
colorT.a = 0.1f;
EQUIPtext.color = colorT;
A =!A;
}
}
}
openOption = true;
}
if(Index2 == 0){
if(Index == i){
if(Inventory[i].ItemId == 0){
if(Playerdata.HP != Playerdata.HPMAX){
t = false;
Inventory[i].capacity--;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.HP += 20;
A =!A;
}
}
if(Inventory[i].ItemId == 1){
t = false;
Inventory[i].capacity--;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.poisened = false;
A =!A;
}
if(Inventory[i].ItemId == 2){
t = false;
Inventory[i].capacity -= 10;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.amount += 10;
A =!A;
}
if(Inventory[i].ItemId == 3){
if(faceDoor){
t = false;
Inventory[i].capacity--;
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Playerdata.UseKey = false;
A =!A;
}
}
if(Inventory[i].ItemId == 4)
{
Color colorT = saveColor;
colorT.a = 0.1f;
USEtext.color = colorT;
A =!A;
}
if(Inventory[i].ItemId == 5)
{
Color colorT = saveColor;
colorT.a = 0.1f;
USEtext.color = colorT;
A =!A;
}
}
openOption = true;
}
}
//======Item Caoacity = 0 Erase ===================================================================
if(Inventory[i].capacity <= 0){
testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
Destroy(testText.gameObject);
Inventory.Remove(Inventory[i]);
openOption = false;
itemOption.SetActive(false);
//icon.gameObject.SetActive(true);
//iconMini.gameObject.SetActive(false);
return;
}
}
//========================================================================================================================
}
//=====CHECK FOR ITEM IF EXIST AND ADD ITEM TO INVENTORY ================================================================================================
public void AddItem(int id) {
Item itemADD = data.fetchItem(id);
if(CheckForItemExist(itemADD)) {
for (int i = 0; i < Inventory.Count; i++) {
if(Inventory[i].ItemId == id) {
t = false;
Inventory[i].capacity ++;
testText = GameObject.Find(itemADD.Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
Debug.Log (testText.text);
if(Inventory[i].Itemtype == Item.ItemType.ammo) {
Inventory[i].capacity += 10;
Inventory[i].capacity -= 1;
testText = GameObject.Find(itemADD.Itemname).GetComponent<Text>();
testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
}
break;
}
}
}else{
for (int i = 0; i < Inventory.Count; i++) {
if(Inventory[i].ItemId == -1){
t = true;
Inventory[i] = itemADD;
DesplayInventory();
}
}
}
}
//====================================================================================================
bool CheckForItemExist(Item item) {
for (int i = 0; i < Inventory.Count; i++)
if(Inventory[i].ItemId == item.ItemId)
return true;
return false;
}
//====================================================================================================
public void DesplayInventory() {
for (int i = 0; i < Inventory.Count; i++) {
var _text =Instantiate(Resources.Load("Text",typeof (Text)))as Text;
testText =_text;
_text.transform.position = panel.transform.position;
_text.transform.SetParent(panel);
_text.transform.localScale = new Vector3(1,1,1);
break;
}
}
}
//===========================================================================================================
and here is the Item script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
[System.Serializable]
public class Item {
public int ItemId;
public string Itemname;
public ItemType Itemtype;
public int ItemPower;
public int capacity;
public enum ItemType
{
weapon,
spells,
consumable,
ammo,
}
public Item(int id,string name,int power,ItemType type,int cap)
{
capacity = cap;
ItemId = id;
Itemname = name;
ItemPower = power;
Itemtype = type ;
}
public Item()
{
this.ItemId = -1;
}
}
and here is the item Data Base script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class ItemDatabase : MonoBehaviour {
public List<Item> items = new List<Item>();
void Start()
{
items.Add (new Item (0, "Potion", 0, Item.ItemType.consumable,1));
items.Add (new Item (1, "Antidot", 0, Item.ItemType.consumable, 1));
items.Add (new Item (2, "Arrows", 0, Item.ItemType.ammo,10));
items.Add (new Item (3, "KEY", 0, Item.ItemType.consumable,1));
items.Add (new Item (4, "sword", 15, Item.ItemType.weapon,1));
items.Add (new Item (5, "bow", 50, Item.ItemType.weapon,1));
}
public Item fetchItem(int id)
{
for (int i = 0 ; i < items.Count;i++)
if(items[i].ItemId == id)
return items[i];
return null;
}
}
It looks like you are missing the Serializeable attribute.
Add it to your Item class like so ->
[Serializable]
public class Item {
///Your code here
}

Cannot call or set a variable from another script in C#

EDIT Full Scripts:
SoldierController Script (removed few variables due to character limitaton). I have declared 1 new variable called DontMove and want this to be called from the ElevatorOpen script. Issue I am having is calling this script even though this is set to static and public.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class SoldierController : MonoBehaviour
{
#region Variables
public Transform gunPoint;
public GameObject bulletPrefab;
//Components
protected Animator animator;
private GameObject camera;
private Camera cam;
public GameObject splashFX;
public AudioClip gunShotSound;
//action variables
public static bool dontMove = false;
public float walkSpeed = 1.35f;
bool canwalk = true;
float moveSpeed;
public float runSpeed = 1f;
public float rotationSpeed = 20f;
bool isMoving = false;
public bool walking = true;
bool areWalking;
Vector3 newVelocity;
Vector3 inputVec;
//aiming/shooting variables
bool canAim;
bool canFire = true;
public bool aiming = true;
bool isAiming = false;
public bool grenading = true;
bool isGrenading;
bool canGrenade = true;
int weaponType = 0;
//Weapon Prefabs
GameObject pistol;
GameObject rifle;
GameObject launcher;
GameObject heavy;
#endregion
#region Initialization
void Start()
{
canMove = true;
//dontMove = false;
//set the animator component
animator = GetComponentInChildren<Animator>();
//sets the weight on any additional layers to 1
if (animator.layerCount >= 2)
{
animator.SetLayerWeight(1, 1);
}
//Get the camera
camera = GameObject.FindGameObjectWithTag("MainCamera");
cam = camera.GetComponent<Camera>();
//sets the Weapon to 1 in the animator
weaponType = 1;
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
#endregion
#region Update
void Update()
{
x = Input.GetAxisRaw("Horizontal");
//z = Input.GetAxisRaw("Vertical");
inputVec = new Vector3(x, 0, z);
if (animator)
{
CoverUpdate();
JumpingUpdate();
if (!isSwimming) //character can't do any actions while swimming
{
if (Input.GetKeyDown(KeyCode.LeftControl) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetMouseButtonDown(0) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetButton("Fire2") && canAim && aiming)
{
isAiming = true;
}
else
{
isAiming = false;
}
}
}
}
#endregion
#region Fixed/Late Updates
void FixedUpdate()
{
CheckForGrounded();
if (!isSwimming) //character is not swimming
{
//gravity
GetComponent<Rigidbody>().AddForce(0, gravity, 0, ForceMode.Acceleration);
if (aircontrol)
AirControl();
//check if we aren't in cover and can move
if (!covered && canMove)
{
if (canPushPull)
{
if (!isPushPulling)
moveSpeed = UpdateMovement(); //if we are not pushpull use normal movement speed
else
moveSpeed = PushPull(); //we are push pulling, use pushpullspeed
}
else
moveSpeed = UpdateMovement();
}
}
else //character is swimming
{
moveSpeed = Swimming();
}
}
void LateUpdate()
{
//Get local velocity of charcter
float velocityXel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).x;
float velocityZel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).z;
//Update animator with movement values
animator.SetFloat("Velocity X", velocityXel / runSpeed);
animator.SetFloat("Velocity Z", velocityZel / runSpeed);
//if we are moving, set our animator
if (moveSpeed > 0)
{
isMoving = true;
animator.SetBool("Moving", true);
}
else
{
isMoving = false;
animator.SetBool("Moving", false);
}
}
#endregion
void RotateTowardsMovementDir()
{
// Rotation
if (inputVec != Vector3.zero && !isAiming)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputVec), Time.deltaTime * rotationSpeed);
}
}
#region UpdateMovement
float UpdateMovement()
{
Vector3 motion = inputVec;
if (isGrounded)
{
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//apply velocity based on platform speed to prevent sliding
float platformVelocity = platformSpeed.magnitude * .4f;
Vector3 platformAdjust = platformSpeed * platformVelocity;
//set speed by walking / running
if (areWalking)
{
canAim = false;
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * walkSpeed + platformAdjust;
}
else
{
newVelocity = motion * walkSpeed + platformAdjust;
}
}
else
{
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * runSpeed + platformAdjust;
}
else
{
newVelocity = motion * runSpeed + platformSpeed;
}
}
}
else
{
//if we are falling use momentum
newVelocity = GetComponent<Rigidbody>().velocity;
}
// limit velocity to x and z, by maintaining current y velocity:
newVelocity.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = newVelocity;
if (!isAiming)
RotateTowardsMovementDir();
//if the right mouse button is held look at the mouse cursor
if (isAiming)
{
//make character point at mouse
Quaternion targetRotation;
float rotationSpeed = 40f;
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x, 0, transform.position.z));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, (rotationSpeed * Time.deltaTime) * rotationSpeed);
}
//calculate the rolling time
rollduration -= rolldamp;
if (rollduration > 0)
{
isRolling = true;
}
else
{
isRolling = false;
}
if (isRolling)
{
Vector3 localforward = transform.TransformDirection(0, 0, 1);
GetComponent<Rigidbody>().velocity = localforward * rollSpeed;
}
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region AirControl
void AirControl()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 inputVec = new Vector3(x, 0, z);
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//allow some control the air
GetComponent<Rigidbody>().AddForce(motion * inAirSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
}
#endregion
#region Swimming
float Swimming()
{
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using swimSpeed
GetComponent<Rigidbody>().AddForce(motion * swimSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
RotateTowardsMovementDir();
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region PushPull
float PushPull()
{
//set bools
canAim = false;
canAbility = false;
canCover = false;
canFire = false;
canGrenade = false;
canItem = false;
canJump = false;
canMelee = false;
canReload = false;
canRoll = false;
canSignal = false;
canwalk = false;
isPushPulling = true;
animator.SetBool("PushPull", true);
Vector3 motion = inputVec;
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using pushpull speed
GetComponent<Rigidbody>().velocity = motion * pushPullSpeed;
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region Grounding
void CheckForGrounded()
{
float distanceToGround;
float threshold = .45f;
RaycastHit hit;
Vector3 offset = new Vector3(0, .4f, 0);
if (Physics.Raycast((transform.position + offset), -Vector3.up, out hit, 100f))
{
distanceToGround = hit.distance;
if (distanceToGround < threshold)
{
isGrounded = true;
//moving platforms
if (hit.transform.tag == "Platform")
{
//get platform script from collided platform
Platform platformScript = hit.transform.GetComponent<Platform>();
//check if the platform is moved with physics or if it is animated and get velocity from it
if (platformScript.animated)
{
platformSpeed = platformScript.velocity;
platformAnimated = true;
}
if (!platformScript.animated)
{
platformSpeed = hit.transform.GetComponent<Rigidbody>().velocity;
}
//get the platform rotation to pass into our character when they are on a platform
platformFacing = hit.transform.rotation;
}
else
{
//if we are not on a platform, reset platform variables
platformSpeed = new Vector3(0, 0, 0);
platformFacing.eulerAngles = new Vector3(0, 0, 0);
Platform platformScript = null;
float platformVelocity = 0f;
}
}
else
{
isGrounded = false;
}
}
}
#endregion
#region Cover
void CoverUpdate()
{
/*
if (covering && !isSwimming)
{
//check if we press cover button
if (Input.GetButtonDown("Cover") && canCover && !covered)
{
//set variables
animator.SetBool("Moving", false);
Input.ResetInputAxes();
isMoving = false;
animator.SetBool("Moving", false);
covered = true;
canReload = true;
canCover = false;
canItem = false;
canMelee = false;
canFire = false;
canItem = false;
canGrenade = false;
canJump = false;
cover = 1;
animator.SetInteger("Cover", 1);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
}
else
{
//if we are already in cover and press the cover button, get out of cover
if (Input.GetButtonDown("Cover") && covered == true)
{
//set the animation back to idle
animator.SetInteger("Cover", 3);
//set variables
cover = 0;
covered = false;
canCover = true;
canAbility = true;
canAim = true;
canItem = true;
canGrenade = true;
canFire = true;
}
}
}*/
}
#endregion
#region Jumping
void JumpingUpdate()
{
if (!isSwimming) //if character is not swimming
{
//If the character is on the ground
if (isGrounded)
{
//set the animation back to idle
animator.SetInteger("Jumping", 0);
//set variables
jumped = false;
//check if we press jump button
if (canJump && Input.GetButtonDown("Jump") && cover != 1)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
animator.SetInteger("Jumping", 2);
}
}
else
{
//set bools
canDoubleJump = true;
if (!falling && !jumped)
{
//set the animation back to idle
animator.SetInteger("Jumping", 2);
falling = true;
}
//if double jumping is allowed and jump is pressed, do a double jump
if (canDoubleJump && doublejumping && Input.GetButtonDown("Jump") && doublejumped != true && doublejumping)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += doublejumpSpeed * Vector3.up;
//set the animation to double jump
animator.SetInteger("Jumping", 3);
//set variables
canJump = false;
doublejumped = true;
isJumping = true;
falling = false;
jumped = false;
}
}
}
else //characer is swimming
{
//check if we press jump button
if (canSwim && Input.GetButtonDown("Jump"))
{
if (x != 0 || z != 0) //if the character movement input is not 0, swim in facing direction
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += swimBurstSpeed * transform.forward;
animator.SetTrigger("SwimBurst");
}
else //we are not trying to move the character, jump up
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity = jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
canJump = false;
isJumping = true;
canDoubleJump = true;
jumped = true;
animator.SetInteger("Jumping", 2);
}
}
}
}
#endregion
#region Misc Methods
void Rolling()
{
StartCoroutine(COPlayOneShot("Rolling"));
covered = false;
canCover = false;
cover = 0;
animator.SetInteger("Cover", 0);
isRolling = true;
}
void Fire()
{
StartCoroutine(COPlayOneShot("Fire"));
(Instantiate(bulletPrefab, gunPoint.position, transform.root.rotation) as GameObject).GetComponent<BulletController>().damage = 20;
StartCoroutine(WeaponCooldown());
GetComponent<AudioSource>().PlayOneShot(gunShotSound);
}
IEnumerator WeaponCooldown()
{
canFire = false;
yield return new WaitForSeconds(0.1f);
canFire = true;
}
void Ability()
{
StartCoroutine(COPlayOneShot("Ability"));
}
void Item()
{
StartCoroutine(COPlayOneShot("Item"));
}
void Grenade()
{
StartCoroutine(COGrenade());
isGrenading = true;
}
void Reload()
{
StartCoroutine(COReload(weaponType));
isReloading = true;
}
void Signal()
{
StartCoroutine(COPlayOneShot("Signal"));
}
void Melee()
{
StartCoroutine(COMelee());
isMelee = true;
}
void Pain()
{
StartCoroutine(COPlayOneShot("Pain"));
}
//plays a random death# animation between 1-3
void Death()
{
//stop character movement
animator.SetBool("Moving", true);
Input.ResetInputAxes();
isMoving = false;
int deathnumber = 5;
animator.SetInteger("Death", deathnumber);
}
#endregion
#region CORoutines
//function to play a one shot animation
public IEnumerator COPlayOneShot(string paramName)
{
animator.SetBool(paramName, true);
yield return null;
animator.SetBool(paramName, false);
}
//function to switch weapons
public IEnumerator COSwitchWeapon(string weaponname, int weaponnumber)
{
//sets Weapon to 0 first to reset
animator.SetInteger(weaponname, 0);
yield return null;
yield return null;
animator.SetInteger(weaponname, weaponnumber);
}
//function to reload
public IEnumerator COReload(int weapon)
{
//sets Weapon to 0 first to reset
animator.SetBool("Reload", true);
yield return null;
animator.SetBool("Reload", false);
float wait = 0;
if (weaponType == 1 || weaponType == 2)
{
wait = 1.85f;
}
if (weaponType == 3 || weaponType == 4)
{
wait = 3f;
}
yield return new WaitForSeconds(wait);
isReloading = false;
}
//function to grenade
IEnumerator COGrenade()
{
//sets Weapon to 0 first to reset
animator.SetBool("Grenade", true);
yield return null;
animator.SetBool("Grenade", false);
yield return new WaitForSeconds(1);
isGrenading = false;
}
//function to Melee
IEnumerator COMelee()
{
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = false;
isMoving = false;
animator.SetTrigger("Melee");
yield return new WaitForSeconds(.7f);
isMelee = false;
canMove = true;
}
IEnumerator COKnockback()
{
StartCoroutine(COPlayOneShot("Knockback"));
return null;
}
public IEnumerator CODazed()
{
StartCoroutine(COPlayOneShot("Dazed"));
Debug.Log("Cant Move");
canMove = false;
canFire = false;
canAim = false;
canJump = false;
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
yield return new WaitForSeconds(3.0f);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = true;
canFire = true;
canAim = true;
canJump = true;
}
#endregion
#region WeaponSwitching
void WeaponSwitch()
{
weaponType++;
if (weaponType == 1)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
if (weaponType == 2)
{
//enables rifle, disables other weapons
pistol.SetActive(false);
rifle.SetActive(true);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 2));
}
if (weaponType == 3)
{
//enables launcher, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(true);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 3));
}
if (weaponType == 4)
{
//enables heavy, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(true);
StartCoroutine(COSwitchWeapon("Weapon", 4));
}
if (weaponType == 5)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
weaponType = 1;
}
}
#endregion
}
And finally the elevatorOPen script:
using UnityEngine;
using System.Collections;
public class ElevatorOpen : MonoBehaviour
{
private Animator animator;
public AudioClip ElevatorBing;
void Awake ()
{
animator = GetComponent <Animator>();
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 1);
GetComponent<AudioSource>().PlayOneShot(ElevatorBing);
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 0);
SoldierController.dontMove = true;
}
}
}
This has been addressed. This is a bug with Unity 5 Beta - Spoke to a member of staff who provided me the latest version of Unity, which has fixed the issue.

Categories