Search code examples
c#unity-game-enginemonodevelopgameobject

Accessing a GameObject in Unity with Different Copies


I'm creating a Quest System in my RPG (Role-Plating Game) and it can be get through an NPC (Non-Player Character). I've attach a script on my main character that can check whether or not you've get a quest from an NPC. Here's the code:

public class QuestTracker : MonoBehaviour
{
    public QuestGiver questGiver;
    public Button AcceptQuest;
    public OpenQuestWindow questWindow;

    public void acceptQuest()
    {
        questGiver.questAccepted = true;
    }
}

Now I've attach a script on my NPC for them to give a quest to the player. Here's the code for the NPC:

 public class QuestGiver : MonoBehaviour
 {
    public bool questAccepted = false;
 }

When the player clicks on the NPC, a window will appear which will show the player what will be his/her quest objective. For now, I've created 2 NPC's and attach them both the QuestGiver script. Here's some screenshot:

enter image description here enter image description here

On the accept button, I've used the acceptQuest() function on my QuestTracker which is attached to the player, but I can't set a specific value for QuestGiver because I have multiple copies of NPC not just one.

enter image description here

What I want is to set the QuestGiver on the player via runtime. I know it can be implemented by using OnMouseOver() function or Raycast. I know the logic, but I don't know how to implement it.


Solution

  • I think using static variable can solve your problem. Set player questGiver as static.

    public class QuestTracker : MonoBehaviour
    {
        public static QuestGiver questGiver;
        public Button AcceptQuest;
        public OpenQuestWindow questWindow;
    
        public void acceptQuest()
        {
            questGiver.questAccepted = true;
        }
    }
    

    And then when an Npc make a quest, change players questGiver via Npc's script.

    void OnMouseDown()
    {
        QuestTracker.questGiver = this;
    }
    

    Edit: By the way, you will not see questGiver variable in inspector when you change it as static. Test it with Debug.Log().