Home > Net >  How to make object appear when a certain torso is called using C# in Unity
How to make object appear when a certain torso is called using C# in Unity

Time:12-05

This is the code I used for a tutorial

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Trial_Changer : MonoBehaviour
{
   
  
        [Header("Sprite To Change")]
        public SpriteRenderer bodyPart;

        [Header("Sprites to Cycle Through")]
        public List<Sprite> options = new List<Sprite>();

    public static int currentTorsoOption = 0;

    public void NextOption ()
    {
        currentTorsoOption  ;
        if (currentTorsoOption >= options.Count)
        { currentTorsoOption = 0; }
        

        bodyPart.sprite = options[currentTorsoOption];

    }

    public void PreviousOption()
    {
        currentTorsoOption--;
        if (currentTorsoOption <= 0)
        { currentTorsoOption = options.Count - 1; }
        

        bodyPart.sprite = options[currentTorsoOption];

    }
}

**This is the code I am using to try to say "if torso 2 is called, create object" **

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpeechAppears : MonoBehaviour
{
    public GameObject speechBubbleTOSpawn;
    private int Torso = Trial_Changer.currentTorsoOption;

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

      

    }

    // Update is called once per frame
    void Update()
    {
        if (Torso == 2)
        {
            Instantiate(speechBubbleTOSpawn);
        }

    }
}

Except the torso just appears always. What do I do to fix this?

I want an object to appear when torso 2 is on the screen but instead the object is just always present. What do I do ?

CodePudding user response:

The culprit is this line :

private int Torso = Trial_Changer.currentTorsoOption;

Since you assign value Torso only once at the start of the game, its value always be the same.

Try this :

private int Torso => Trial_Changer.currentTorsoOption;

This change Torso from a field to a property, and when Torso is used, it will read the current value of Trial_Changer.currentTorsoOption.

  • Related