- Home /
Switching between items after being picked up?
Hello! I'm making a game where you can collect "letter" pages. The player has a Clipboard in which he can view the collected pages. I made a code that worked exactly how I wanted, though it only worked when there were only 2 of these pages. I want to have a lot more pages, but if I did wth the code I'm using it will be a lot longer, when I just add one more page. So having around 10 pages would be a lot harder than it should. I'm new to making games, and this is the first code I've ever written, here it is:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PageFinder : MonoBehaviour { public GameObject page1; public GameObject page2;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1) && Page2Trigger.isPicked == true && Page1Trigger.isPicked == true)
{
page1.SetActive(true);
page2.SetActive(false);
}
if (Input.GetKeyDown(KeyCode.Alpha2) && Page2Trigger.isPicked == true && Page1Trigger.isPicked == true)
{
page1.SetActive(false);
page2.SetActive(true);
}
}
}
Answer by Zaeran · Oct 27, 2019 at 03:40 PM
Store your pages in a List, then you can access them with a direct index.
I.e.
public List<GameObject>() pages;
//Disable all pages
foreach(GameObject g in pages) {
g.SetActive(false);
}
//Set page 5 active
pages[4].SetActive(true);
How do I use this?
I put the "foreach and pages[4] in the update. But how do I make a button that disables them after I pick them up? So that they won't get disabled before I can pick them up.
Do I add that to the code or replace it with something? Sorry, I'm new and don't really know a lot yet.
No worries :)
What you can do is only add them to the list once they've been picked up. So create a method like this:
public void PickupPage(GameObject page)
{
if(!pages.Contains(page))
{
pages.Add(page)
}
}
Now your foreach loop will only affect the pages you've picked up, ins$$anonymous$$d of all if them. Just call that method each time a new page is picked up
Your answer
Follow this Question
Related Questions
Flickering when switching between GameObjects 0 Answers
physics.OverlapSphere colliders 1 Answer
Entering/Exiting Vehicle 90% complete 1 Answer
How to change scenes by touching objects? 2 Answers
Swappable clothing and armor help 1 Answer