So I created a method to populate the inventory system I have created in Unity, however I can't seem to figure out a way to order them in alphabetical order. Each button is created as a child of the button holder panel which is a game object variable. This method is called whenever the player picks something up.
private void Populate_Inventory ( )
{
Button btn_CurrentItem;
int int_Count;
for ( int_Count = int_PreviousCount; int_Count < strList_Inventory.Count; int_Count++ )
{
btn_CurrentItem = Instantiate ( btn_Item, pnl_ButtonHolder.transform );
btn_CurrentItem.name = strList_Inventory [ int_Count ];
btn_CurrentItem.GetComponentInChildren<Text> ( ).text = strList_Inventory [ int_Count ];
btn_CurrentItem.gameObject.AddComponent<Inventory_Item> ( );
btn_CurrentItem.GetComponent<Inventory_Item> ( ).str_Name = cls_Pickup.str_PickupName;
btn_CurrentItem.GetComponent<Inventory_Item> ( ).str_Information = cls_Pickup.str_PickupInformation;
int_PreviousCount = int_Count;
}
int_PreviousCount++;
}
If anyone can help it would be very appreciated.
Jonathan Palmer
The primary issue with this approach is that you're adding single buttons at a time whenever you pick up an item, and those buttons are created as children of the pnl_ButtonHolder object, but your method has no knowledge of previous buttons that have been created.
Option 1 (Bad)
You can use the GetComponentsInChildren<Button>() method on the pnl_ButtonHolder object to get all of the button components that have been previously created once you've added a new button, and then sort your buttons according to their name.
This isn't ideal as GetComponentsInChildren<>() is an expensive method, and doesn't make use of the idea of an Inventory very well.
Option 2 (Good)
Create an Inventory class that manages your actual inventory, including sorting items. It might look something like this:
public class Inventory_Button : MonoBehaviour
{
public Button button = default;
public void Initialize(Intenvory_Item item)
{
button.name = item.name;
// Other work here.
}
}
public class Inventory : MonoBehaviour
{
public GameObject inventoryItemPrefab = default;
public Transform inventoryParent = default;
private List<Inventory_Item> _inventory = new List<Inventory_Item>();
private List<Inventory_Button> _inventoryButtons = new List<Inventory_Button>();
public void AddItem(Intenvory_Item item)
{
_inventory.Add(item);
Inventory_Button button = GameObject.Instantiate(inventoryItemPrefab, inventoryParent).GetComponent<Inventory_Button>();
button.Initialize(item);
_inventoryButtons.Add(button);
_inventoryButtons.Sort((x, y) => x.name.CompareTo(y.name));
}
public void RemoveItem(Inventory_Item item)
{
// Do work to remove the item.
}
}
This kind of setup is useful for several reasons:
Your inventory management is now handled by a single class rather than a collection of objects. This makes it easy to interact with.
It will make removing items much easier in the future. With your current implementation, it looks like you'd have a difficult time removing an item from the player's inventory.
It separates responsibility between an Inventory class, an Inventory_Item class, and an Inventory_Button class, each of which stands on its own and works together.
A few final notes:
I've left out some details in the two classes above. You should fill them in to fit the needs of your game.
You can be more efficient with sorting by using something like Insertion Sort. This solution will get the job done.
Using prefixes for naming your variables can be quite confusing to people trying to read your code. I recommend you check out a style guide. There's a great one here.
Related
I'm building an ASPX web page where some links will be visible or invisible depending on the user's access level. My thought was rather than create multiple functions and turn each link on or off, I could keep things neat and tidy by making List<LinkButton> members, like:
private List<LinkButton> adminButtons = new List<LinkButton>();
private List<LinkButton> guestButtons = new List<LinkButton>();
private List<LinkButton> userButtons = new List<LinkButton>();
Then I'd call one function to make them all visible or invisible.
private void DisplayButtons(List<LinkButton> linkButtons, bool displayButtons) {
for (int i = 0; i < linkButtons.Count; i++) {
linkButtons[i].Visible = displayButtons;
}
}
But I hit two snags. Firstly, I couldn't figure out how to initialize the lists with the links. For example, I've got asp:LinkButtons with IDs like ID='Link_UserManagement', ID='Link_InventoryManagement', et cetera. I can do this in the ASPX.CS file, and it works:
Link_UserManagement.Visible = false;
Link_InventoryManagement.Visble = true;
But this doesn't work:
private List<LinkButton> adminButtons = new List<LinkButton>() { Link_UserManagement }
And then if I try adding them this way, then the List count increases, but the values are null:
adminButtons.Add(Link_UserManagement);
So obviously I don't understand something about how these links work. My question is, why isn't this working the way I thought it would?
Secondly, if there's a better way to go about hiding and showing content based on a user's access level, I'm open to suggestions.
I have a redux like state tree that looks as such (reduced down for readability).
public class StateTree : StateBase
{
public List<News> News;
public List<Opinion> Opinions;
}
I cannot mutate an object, I must replace it, because the StateBase I am using has a bunch of logic that requires you to not mutate (similar to redux).
These objects have visual representations that I am dragging and dropping. My visual objects are UIObject and they represent a domain object, which can be one of several types. I created an IMoveable interface for my domain objects that can be dragged and dropped (through a UIObject)
I have no control over the UIObject creation so when a UIObject is dropped I dont have a link directly to my domain object. As such I have tried to create a Dictionary<UIObject, IMoveable>
I can now find my IMoveable (domain object), but I do not know where in the state tree it is. I could for loop over each item in each list in my StateTree and check if it's the item and if so replace that array index with a new item. I would prefer not to do that.
Here is my drag end, where I get the domain object and pass it on to my reducer. (Just a function that returns a new state)
IMoveable Actor = movementManager.GetIMoveableFromDroppedObject(droppedObject);
Store.Dispatch<MoveableAction>(new MoveableAction() {
ActionType = "MoveObject", ObjectPosition = ObjectPosition, Actor = Actor
});
This store dispatch gets picked up and does the following
public override StateTree Reduce(StateTree state, MoveableAction action)
{
switch (action.ActionType)
{
case "MoveObject":
var moveable = action.Actor;
IMoveable obj = (IMoveable)moveable.Clone();
obj.UpdatePosition(action.ObjectPosition);
moveable = obj;
break;
}
return state;
}
This doesn't seem to function as expected, the original List that contains the IMoveable I found in my dictionary is unaffected. I thought these objects were passed by ref and therefore I could just replace it but it seems to not be so simple. Is there a way to accomplish what I want to do, or am I forced to go through every possible list/type and do a comparison?
I need to instantiate an object at runtime, where the number of objects are based on a txt file (number of lines). All objects need to be clickable (onClick() event) and when they are pressed a tooltip must appear. Tooltips are specific ( Object1 -> Tooltip1, Object2 -> Tooltip2). Tooltips are just a Panel and they consist in some other Panels and Buttons. One of these create a new Panel. Also these Panel are specific (Tooltip1 -> Panel1 and so on). I create a prefab for each of three objects.
So, Object1 - onClick() -> Tooltip1 - onClick() -> Panel1. At runtime.
How can I keep reference of an object create at runtime?
My first solution:
Create a Empty object and assign a script to it with a public variable (Object prefab).
Instantiate Object prefab:
for (int i = 0; i < numberOfObject; i++)
{
var instance = Instantiate(m_ObjectPrefab);
instance.name = "Object_" + m_nameObject[i];
Instantiate one Tooltip for each Object:
var instancePanelTooltip = Instantiate(m_panelTooltipPrefab, m_canvas.transform);
instancePanelTooltip.name = "Panel_Tooltip_" + m_nameObject[i];
Instantiate one Panel for each Tooltip:
var instancePanel = Instantiate(m_panelPrefab, m_canvas.transform);
instancePanel.name = "Panel_" + m_nameObject[i];
instancePanel.SetActive(false);
instancePanelTooltip.SetActive(false);
Add event handler for Object
DetectClickOnObject scriptDetectClickPanelTooltip = instance.AddComponent<DetectClickOnObject>();
scriptDetectClickPanelTooltip.SetTooltip(instancePanelTooltip);
Add event handler for button on Tooltip
DetectClickOnObject scriptDetectClickPanel = buttonOpenPanel.AddComponent<DetectClickOnObject>();
scriptDetectClickPanel.SetPanel(instancePanel);
}
Issue with this solution:
I will instantiate 3 object (Object, Tooltip, Panel) for each line of file. For Object it is okay, but it is not with Tooltip and Panel, because only one Tooltip is active among all (same for Panel).
I just avoid the problem of reference because I create in the same place all objects (one for each element), but what can I do if I need to get access to Tooltip2 or Panel3 without a reference (I am trying to avoid Find and similar).
Conclusion of the first solution: Solution is working, but I think there is a better way of doing that (avoid create so much object and keep reference in the right way).
My second solution (guidelines):
I am trying to create a class to keep reference of all object create at runtime.
I want to create an instance of Object for each lines, but I want just one Tooltip and Panel for all Object and changing properties according to Object clicked. So Object is create at runtime, but Tooltip and Panel are already in the scene but not active.
I need a Register Event Manager to add onClick() event at runtime on Objects and it need to handle properties to be set on Tooltip and Panel based on clicked Object.
Problems with second solution: Referring to 1) I tried to follow that, but I ended up with nothing. I am lost between singleton, static and something else. Referring to 2) I think it can be easy, I just need to cut away some of the first solution. Referring to 3) I can not do more if I do not have a class reference manager.
What I am looking for:
Is first solution so bad? If I look at code I am disgusted by it, it is far away from elegance (or something similar).
Can you suggest me how can I keep track of reference create at runtime with a Reference Manager? And how use it?
#Behnam Sattar suggestion:
As DataModell class,
public class DataModelPOI
{
public string m_namePOI { get; private set; }
public string m_locationPOI { get; private set; }
public Vector2d m_positionPOI { get; private set; }
public GameObject m_gameObject_POI;
public GameObject m_gameObjectTooltip;
public GameObject m_gameObjectPanel;
public DataModelPOI(string namePOI, string locationPOI, Vector2d positionPOI)
{
this.m_namePOI = namePOI;
this.m_locationPOI = locationPOI;
this.m_positionPOI = positionPOI;
}
}
As DataManager,
public class POIManager : MonoBehaviour
{
List<DataModelPOI> dataCollectionPOI = new List<DataModelPOI>();
void Start()
{
ReadFile();
SpawnPOI();
}
void Update()
{
int count = dataCollectionPOI.Count;
for (int i = 0; i < count; i++)
{
UpdatePOIPosition();
}
}
void ReadFile()
{
TakeDataFromFile();
for (int i = 0; i < ength; i++)
{
DataModelPOI dataPOI = new DataModelPOI(m_namePoi[i], m_namePoi[i], _locations[i]);
dataCollectionPOI.Add(dataPOI);
}
}
private void SpawnPOI()
{
for (int i = 0; i < dataCollectionPOI.Count; i++)
{
DataModelPOI dataPOI = dataCollectionPOI[i];
var instance = Instantiate(m_POIPrefab);
instance.name = "POI_" + m_namePoi[i];
dataPOI.m_gameObject_POI = instance;
dataPOI.m_gameObjectTooltip = m_panelTooltipPOI;
dataPOI.m_gameObjectPanel = m_panelPOI;
}
}
Now I need to register Event associate to GameObject instantiate before. I want to do that in my EventManager. How can I point to dataCollectionPOI in EventManager class created and feeded in DataManager? Thanks for your time.
Based on my understanding your question is mostly a design question. In first part of this answer, I'm giving you a suggestion for doing the design and keeping a reference to your objects. In second part I'll give you some tips regarding performance.
[I'm using RootObject instead of Object to refer you the main GameObject you create.]
Design
Let's break down our needs and then come up with a solution for each.
First we want to read some text file and then get some data from that. This data will be used later for creation of GameObjects. For now let's just focus on the data itself.
What we want here is a manager class which reads the file for us and stores the data in some form. We access this manager later and ask for our data in order to create the GameObjects.
This manager class stores our data in a collection of data objects [notice here we're talking about plain objects and not Unity's GameObjects]. You need to design this data class based on each line of text you have. Optionally, you can also keep the references to GameObjects here too.
Assume you're reading three string values from each line, named ValueOne, ValueTwo, and ValueThree, and you want to keep reference to three GameObjects called RootObject, ToolTip and Panel. For such purpose you can define following class:
public class DataModel {
// Values read from text file.
public string valueOne { get; private set; }
public string valueTwo { get; private set; }
public string valueThree { get; private set; }
// Placeholders for GameObjecs created at runtime.
public GameObject rootObject;
public GameObject tooltipObject;
public GameObject panelObject;
public DataModel(string valueOne, string valueTwo, string valueThree){
this.valueOne = valueOne;
this.valueTwo = valueTwo;
this.valueThree = valueThree;
}
}
Then in your manager class you can create a collection (a List for example) for holding your data. Your manager class should read the text file at some point and populate this list with instances of DataModel. It will be something like this:
public class DataManager {
List<DataModel> dataCollection = new List<DataModel>();
public void ReadFile() {
// Here you need to read the file and get the values you need.
// The actual code should be different from what I'm putting here.
foreach(string line in lines) {
// You get valueOne, valueTwo and valueThree
// from each line and maybe prepare them
// (maybe you need conversion from string to int)
DataModel data = new DataModel(valueOne, valueTwo, valueThree);
dataCollection.Add(data);
}
}
}
After you call the method on manager to read the data, you'll have your data prepared for you whenever you want to use it.
It's time to create objects based on the data and save the reference.
for (int i = 0; i++; i <= manager.dataCollection.Count) {
DataModel data = manager.dataCollection[i];
data.rootObject = instantiate() // You instantiate the root GameObject here.
data.tooltip = instantiate() // You instantiate the tooltop GameObject here.
data.panel = instantiate() // You instantiate the panel GameObject here.
}
Done. Now you have a manager class which has reference to all the data and also GameObjects which are created based on this data.
Performance
It might not be a good idea to do this all in runtime as it might cause frame drops in your game. If this is a problem you can try object pooling. If you search for that you should be able to find great tutorials on how to perform object pooling.
If you ended up not using object pooling, you can still remedy any performance drops by instantiating only one GameObject per frame. This can be done using Coroutines. You just need to do a yield return new WaitForEndOfFrame() in your loop of instantiation.
Final Note
Keep in mind that this all a suggestion and I don't think there is one single best answer to your question. Make sure you try to understand what tools are at your disposal and try them all before deciding on one solution. :)
You're basically on the right track, but you can separate (or 'objectify' ;) what scripts keep what references. Keep scripts that manage the internal workings of your prefabs in those prefabs.
A singleton-like pattern for the Tooltips is definitely the way to go. For where you can't use a singleton, such as in the clickable objects, use something more akin to dependency injection (to save on Finds) and pre-stored reference:
var obj = Instantiate(...);
obj.GetComponent<SomeManagerScript>.SomeDependency = SingletonInstance;
obj.GetComponent<StoredReferenceScript>.TextPanel.Text = "Some Text";
As to events, you can handle them a couple of ways. One, each clickable manages its own bindings/functionality; or two, each clickable notifies a global manager that it was clicked on, and the manager determines the actions to take.
Basically you need to create an object at Runtime and set the data for that specific object.
here is the simplest way to do that
first of all create scripts first one can Create an object at runtime and second one is your data setter script that attach with your prefab
so, when ever you create an object at runtime you can pick a reference of the dataSetter and set the specific data.
Hope below given code may useful to you.
GameObject object = Instantiate(gameObject,parent)
DataSetter s = object.GetComponent<DataSetter>().toolTip = "YourTooltip";
in DataSetter script tool tip is a string variable.
you can also declare text variable and assign a text to that.
I have implemented a list system which records the users name, the total amount of points which they have scores and the amount of time it took to do this. Im now having problems with trying to display the list "players" from another class. So within my HighScoresMenu form when trying to display the content of the players list within a the list box, the list box only displays "Game.Player".
Is there any possible solutions to this issue. Any Help would be appreciated.
public partial class MainMenu : Form
{
public static List<Player> GetPlayers(float newScore, float newPoints,
string PlayersName)
{
var players = new List<Player>();
var newPlayer = new Player
{
Name = PlayersName,
Points = newPoints,
Timer = newScore
};
players.Add(newPlayer);
var TopTenLevel1 = players.OrderByDescending(x => x.Timer).Take(10);
return players;
}
}
public partial class HighScoresMenu : Form
{
foreach (var players in MainMenu.GetPlayers(newScore, newPoints,
PlayersName))
{
ListBoxLevel1.Items.Add(players);
}
}
Ok, so to begin, I might not understand your question correctly. What I get from it is that your list view is displaying the name of the object, hence the "Game.Player". So you would have to change the following:
ListBoxLevel1.Items.Add(players);
to something like the following:
ListBoxLevel1.Items.Add($"Player: {players.Name}, Score: {players.Points}");
I'm not sure what your list box is taking as a parameter in the Items.Add(); method, so this answer is assuming it's a string.
I had this problem also few years ago: The function GetPlayers is static, that means that the content (value) or the variable isn't accessible from other classes.
You need to remove 'static' and initiate the MainMenu in the HighScoresMenu class like this:
//MainMenu
public static List<Player> GetPlayers(float newScore, float newPoints, string PlayersName)
//HighScoreMenu
MainMenu main = new MainMenu();
menu.GetPlayers(newScore, newPoints, PlayersName);
I hope this will fix the problem (removing keyword 'static' from the function and initiating the MainMenu class)
I would glad to hear if the current situation is solved or not. :) I hope I did remember it good.
Edit
After I took a second look you are foreach looping it as var player.
But loop it as Player player. Because you putted in in the other class as Player object inside a list of Players. Now you are retrieving it as a var.**
So the final conclusion:
public partial class HighScoresMenu : Form
{
foreach (Player players in MainMenu.GetPlayers(newScore, newPoints,
PlayersName))
{
ListBoxLevel1.Items.Add(players.getName());
}
}
I am curious let me know :D
Edit 2
Also letting you know in case of you never know. You are always making just one Player so there isn't actually a list needed and this piece of code:
var TopTenLevel1 = players.OrderByDescending(x => x.Timer).Take(10);
This will order it but you aren't doing anything with it (var 'TopTenLevel1'). Just letting you know :) You could save the ordered list by returning it (overwriting variable also possible).
I have an ItemsControl displaying a collection of files. Those files are sorted by most recent modification, and there's a lot of them.
So, I want to initially only show a small part (say, only 20 or so) of them, and display a button labelled "Show More" that would reveal everything when clicked.
I already have a solution, but it involves using a good old LINQ Take on my view model's source property. I was wondering if there was a cleaner way.
Thanks.
Why not have the object that you assign to the ItemsSource handle this logic - on first assignment, it would report a limited subset of the items. When Show More is clicked, the object is updated to show more (or all entries) and then notifies the framework that the property has changed (e.g. using the IPropertyNotifyChanged).
public class MyItemSource
{
private List<string> source = { ... };
public MyItemSource()
{
this.ShowThisMany = 20;
}
public int ShowThisMany
{
get;
set; // this should call\use the INotifyPropertyChanged interface
}
public IEnumerable<string> this[]
{
return this.source.Take(this.ShowThisMany);
}
}
...
MyItemsSource myItemsSource = new MyItemsSource();
ItemsControl.Source = myItemsSource;
...
void OnShowMoreClicked(...)
{
myItemsSource.ShowThisMany = 50;
}
In order to do this, you need to create some sort of 'view' on your data. There is nothing within the WPF framwork that will give you this functionality for free. In my opinion, a simple bit of Linq, Take(), is a clean and simple solution.