Unity connect a Character Class to a UI Toggle - c#

I am trying to build a Character Selection. When I tick a toggle, it should say "You selected class xy". I already got the active Toggle of the Toggle Group, I just do not know how to connect it to another object.
I divided my Scripts into 3 parts, Data, View and Controller.
My view:
public class ClassSelectionCommonView : MonoBehaviour
{
[SerializeField]
ToggleGroup toggleGroup; // Get the Toggle Group of the Scene
public Toggle GetActiveToggle() // Return the single active Toggle
{
return toggleGroup.ActiveToggles().FirstOrDefault();
}
}
My Data:
public class ClassSelectionCommonData : MonoBehaviour
{
public string ClassName { get; set; } // The characters stats
public float MovementSpeed { get; set; }
public float LifePoints { get; set; }
public float DamageReduction { get; set; }
public float AttackDamageMelee { get; set; }
public float AttackDamageRange { get; set; }
public float AttackSpeed { get; set; }
public float GoldFind { get; set; }
private ClassSelectionCommonData templar = new ClassAlchemist(); // Create Character Classes
private ClassSelectionCommonData inquisitor = new ClassInquisitor();
private ClassSelectionCommonData hunter = new ClassHunter();
private ClassSelectionCommonData warlord = new ClassWarlord();
private ClassSelectionCommonData bandit = new ClassBandit();
private ClassSelectionCommonData alchemist = new ClassAlchemist();
private ClassSelectionCommonData engineer = new ClassEngineer();
private ClassSelectionCommonData thief = new ClassThief();
private ClassSelectionCommonData occultist = new ClassOccultist();
}
And the Controller:
public class ClassSelectionCommonController : MonoBehaviour
{
ClassSelectionCommonData data;
ClassSelectionCommonView view;
private void Start()
{
data = GetComponent<ClassSelectionCommonData>();
view = GetComponent<ClassSelectionCommonView>();
}
public void SelectClass() // "Start" Button pressed
{
Toggle selectedToggle = view.GetActiveToggle(); // Get the active Toggle
// ... ?
}
}
So when I call the Method SelectClass() I do not know how to move on. How could I say that this selectedToggle is class xy?
Thanks a lot!

If there is only script selection issue(Not charachter mesh selection) Then, you should attache both script on the object and enable disable them on UItoggle.

Related

"Load is not allowed to be called from MonoBehaviour constructor" On script that does not inherit from MonoBehaviour

I have two classes; BuildableObject and TempObject. For some reason, Unity is treating TempObject like a MonoBehaviour class in which it throws an error if I use Resources.Load() from the constructor.
Why is this, and how do I fix it?
public abstract class BuildableObject {
public abstract Vector2Int Space { get; set; }
public abstract GameObject Body { get; set; }
public void Init(GridSpace[,] World, Vector2Int pos) {
Vector3 Pos = World[pos.x, pos.y].pos;
//TODO: Optimize
//TODO: Add availibility for multiple tile sizes
Pos.x += Body.transform.lossyScale.x / 6;
Pos.y += Body.transform.lossyScale.y / 6;
Body.transform.position = Pos;
Body.transform.position = new Vector3(Body.transform.position.x,Body.transform.position.y,-5);
Object.Instantiate(Body);
OnPlace();
}
public void OnPlace() { }
public void OnUpdate() { }
public void OnRemove() { }
public void OnInteract(InteractData Data) { }
}
public class TempObject : BuildableObject {
public override Vector2Int Space { get; set; } = new Vector2Int(2, 2);
public override GameObject Body { get; set; }
public TempObject() {
Body = (GameObject)Resources.Load("BuildPrefabs/Test", typeof(GameObject)); //error
}
}
The reason I got an error was because I was instancing TempObject from a MonoBehaviour class:
using UnityEngine;
public class Example : MonoBehaviour {
public BuildableObject Selected = new TempObject(); // real error
}

checking if datagrid has values

I am working on a C# project which includes WPF. I was wondering, If I could somehow check If my data grid contains certain element.
For example,
I have combo box whose itemsSource is some list of objects. Now, when an user selects an item from the combo box and presses the button
below in data grid (in same window) that item shows up.
I want to forbid the user to select same item more than once and for example put MessageBox with error message. How could I do that?
Code
This Window:
public partial class AvioWindowAddNEdit : Window
{
Avio avio;
public enum Stage { ADD, EDIT};
Stage stage;
public AvioWindowAddNEdit(Avio avio, Stage stage = Stage.ADD)
{
InitializeComponent();
this.avio= avio;
this.stage= stage;
textboxCode.DataContext = avio;
comboboxListofFlights.ItemsSource = Aplikacija.Instance.Flights;
comboboxListofFlights.DataContext = avio;
datagridListofFlights.ItemsSource = avio.ListofFlights;
datagridListofFlights.ColumnWidth = new DataGridLength(1, DataGridLengthUnitType.Auto);
if (stage== Stage.EDIT)
{
textboxCode.IsEnabled = false;
}
}
}
Button which adds selected item to data grid:
private void btnAddFlight_Click(object sender, RoutedEventArgs e)
{
avio.ListOfFlights.Add(comboboxListOfFlights.SelectedItem as Flight);
}
Singleton class for loading in all of my data:
class Aplication
{
public ObservableCollection<User> Users { get; set; }
public ObservableCollection<Airport> Airports { get; set; }
public ObservableCollection<Flight> Flights{ get; set; }
public ObservableCollection<Avio> Avios { get; set; }
public string LoggedInUser { get; set; }
private static Aplication instance = new Aplication();
public static Aplication Instance
{
get
{
return instance;
}
}
private Aplication()
{
Users= new ObservableCollection<User>();
Airports = new ObservableCollection<Airport>();
Flights = new ObservableCollection<Flight>();
Avios= new ObservableCollection<Avio>();
FillInData(); //method where I filled in all of these ObservableCollections
}
}
My class:
public class Avio : ObservableObject, ICloneable
{
//observableobject is an object where I implemented INotifyPropertyChanged
private string code;
public string Code
{
get { return code; }
set { code= value; OnPropertyChanged("Code"); }
}
private ObservableCollection<Flight> listOfFlights;
public ObservableCollection<Flight> ListOfFlights
{
get { return listOfFlights; }
set { listOfFlights= value; OnPropertyChanged("ListOfFlights"); }
}
private bool active;
public bool Active
{
get { return active; }
set { active= value; OnPropertyChanged("Active"); }
}
public Avio()
{
active= true;
ListOfFlights = new ObservableCollection<Flight>();
}
public Avio(string code)
{
active= true;
ListOfFlights = new ObservableCollection<Flight>();
Code= code;
}
}
You could use an ObservableCollection as an ItemsSource for your DataGrid. In that way you'll always have easy access to the data via code.
Check out this tutorial as a starting point (this uses ListBox instead of DataGrid, but it's easily adaptable to DataGrid).

How to share a list of objects without giving ability to modify their state?

Let's say I have a class StockMarket which has a list of Companies.
class StockMarket : IStock
{
private static List<IObserverPush> observersPush;
private static List<IObserverPull> observersPull;
public static List<Company> Companies { get; private set; }
public StockMarket()
{
observersPush = new List<IObserverPush>();
observersPull = new List<IObserverPull>();
Companies = new List<Company>() { new Company("Unilever", "UNA", 47.72, 0.77, 1.63, -3.45, "135B"),
new Company("ING Groep", "INGA", 13.40, -0.07, -0.50, -12.38, "60.4B"),
new Company("ArcelorMittal", "MT", 29.50, 0.14, 0.48, 36.05, "54.6B"),
new Company("ASML Holding", "ASML", 167.40, 2.00, 1.21, 36.49, "53.3B"),
new Company("Heineken", "HEIA", 87.66, -0.02, -0.02, 2.80, "49B"),
new Company("RELX", "REN", 18.15, 0.17, 0.95, -0.22, "38.9B"),
new Company("Philips", "PHIA", 35.49, 0.17, 0.47, 7.61, "33.3B"),
new Company("Unibail Rodamco", "UL", 196.40, -0.15, -0.08, -16.78, "20.3B"),
new Company("Akzo Nobel", "AKZA", 75.68, -0.16, -0.21, 0.33, "19.4B"),
new Company("Altice", "ATC", 7.58, 0.16, 2.16, -66.30, "17.6B")};
Thread thread = new Thread(SimulateMarket);
thread.Start();
}
public void Subscribe(IObserverPull o)
{
observersPull.Add(o);
o.UpdateMarket();
}
public void Unsubscribe(IObserverPull o)
{
observersPull.Remove(o);
}
public void Subscribe(IObserverPush o)
{
observersPush.Add(o);
o.UpdateMarket(Companies);
}
public void Unsubscribe(IObserverPush o)
{
observersPush.Remove(o);
}
public void NotifyObservers()
{
foreach(IObserverPush o in observersPush)
{
o.UpdateMarket(Companies);
}
foreach(IObserverPull o in observersPull)
{
o.UpdateMarket();
}
}
public void SimulateMarket()
{
while(observersPush.Count + observersPull.Count > 0)
{
//randomly change property values of companies
//and notify the observers about the changes
}
}
}
Company class has some properties.
public class Company
{
public string Name { get; private set; }
public string Symbol { get; private set; }
public double Price { get; set; }
public double Change { get; set; }
public double ChangePercentageDay { get; set; }
public double ChangePercentageYear { get; set; }
public string Capital { get; private set; }
public Company(string name, string symbol, double price, double change, double changePercentageDay,
double changePercentageYear, string capital)
{
Name = name;
Symbol = symbol;
Price = price;
Change = change;
ChangePercentageDay = changePercentageDay;
ChangePercentageYear = changePercentageYear;
Capital = capital;
}
}
The Forms have references to the StockMarket and they use it to retrieve data about the companies and to display it.
Form 1
public partial class ConcreteObserverPush : Form, IObserverPush
{
private StockMarket stockMarket;
public ConcreteObserverPush()
{
InitializeComponent();
stockMarket = new StockMarket();
stockMarket.Subscribe(this);
}
public void UpdateMarket(List<Company> companies)
{
stockMarketListView.Items.Clear();
foreach(Company c in companies)
{
ListViewItem item = new ListViewItem(c.Symbol);
item.SubItems.Add(c.Price.ToString());
item.SubItems.Add(c.Change.ToString());
item.SubItems.Add(c.ChangePercentageDay.ToString() + "%");
stockMarketListView.Items.Add(item);
}
}
private void ConcreteObserverPush_FormClosing(object sender, FormClosingEventArgs e)
{
stockMarket.Unsubscribe(this);
}
}
Form 2
public partial class ConcreteObserverPull : Form, IObserverPull
{
private StockMarket stockMarket;
public ConcreteObserverPull()
{
InitializeComponent();
stockMarket = new StockMarket();
stockMarket.Subscribe(this);
}
public void UpdateMarket()
{
stockMarketListView.Items.Clear();
foreach (Company c in StockMarket.Companies)
{
ListViewItem item = new ListViewItem(c.Symbol);
item.SubItems.Add(c.Name);
item.SubItems.Add(c.Price.ToString());
item.SubItems.Add(c.Change.ToString());
item.SubItems.Add(c.ChangePercentageDay.ToString() + "%");
item.SubItems.Add(c.ChangePercentageYear.ToString() + "%");
item.SubItems.Add(c.Capital);
stockMarketListView.Items.Add(item);
}
}
private void ConcreteObserverPull_FormClosing(object sender, FormClosingEventArgs e)
{
stockMarket.Unsubscribe(this);
}
}
The problem is that if the Form gets the list of companies through the property on StockMarket it can change their state. However, I want only StockMarket to have the ability to change the state of the company.
So what would be the best way to share Company state with Form when requested and preventing the Form from modifying it.
I know that a possible solution would be to return clones of Company objects, but I believe there should be a better solution.
Any help is appreciated!
The general gist of this would be to make your Company object immutable. Then you would add methods to the StockMarket object to manipulate the Company list and replace entries with new ones when you want to change a value.
Here's a quick example put together in LINQPad of making the Company class immutable and adding an UpdatePrice method to the StockMarket class.
Whether you want to be able to manipulate the Companies property from outside the StockMarket can be handled by returning the list as ReadOnlyCollection so that it's size can't be manipulated by a consumer.
void Main()
{
var sm = new StockMarket();
sm.Companies.Add(new Company("Test", "TST", 50, 0));
sm.UpdatePrice("Test", 45);
var testCompany = sm.Companies.First(x => x.Name == "Test");
Console.WriteLine($"{testCompany.Name},{testCompany.Symbol},{testCompany.Price},{testCompany.Change}");
//Output: Test,TST,45,-5
}
class StockMarket
{
public List<Company> Companies { get; private set; } = new List<Company>();
public void UpdatePrice(string name, double price) {
var index = Companies.FindIndex(x => x.Name == name);
if(index >= 0)
{
var previous = Companies[index];
Companies[index] = new Company(previous.Name, previous.Symbol, price, price - previous.Price);
}
}
}
class Company
{
public Company(string name, string symbol, double price, double change) {
Name = name;
Symbol = symbol;
Price = price;
Change = change;
}
public string Name { get; }
public string Symbol { get; }
public double Price { get; }
public double Change { get; }
///...
}
This would be a solution:
Create the Company class as a Private Inner Class inside of the StockMarket class, that way it'd only be accessible inside of it, and then provide an interface that only includes the get of all the properties and make Company implement it. You would have to make StockMarket's Company list to be the Interface's type.
Any modification you'd have to do you'd do it by casting the interface's List objects into the original class type.
Example:
class Program
{
public static StockMarket stockMarket = new StockMarket();
static void Main(string[] args)
{
}
}
public interface ICompany
{
string Name { get; }
}
public class StockMarket
{
public StockMarket()
{
Companies = SomeWildFunctionThatRetrievesAllCompanies();
}
public void OneWildFunctionThatModifiesACompany()
{
Company dunno = (Company)Companies[0];
dunno.Name = "Modification Made Possible";
}
private List<ICompany> SomeWildFunctionThatRetrievesAllCompanies()
{
return new List<ICompany>(new List<Company>());
}
public List<ICompany> Companies { get; private set; }
private class Company : ICompany
{
public string Name { get; set; }
}
}
Try this:
class Company
{
public Company(Type type,string name,string symbol,double price, double change)
{
if (type.Name == "StockMarket")
{
Name = name;
Symbol = symbol;
Price = price;
Change = change;
}
}
private string Name { get; set; }
private string Symbol { get; set; }
private double Price { get; set; }
private double Change { get; set; }
///...
}
This will allow you to change the state only if the type is StockMarket
like:
class StockMarket
{
public List<Company> Companies { get; set; }
public StockMarket()
{
Companies = new List<Company>();
}
public StockMarket someMethod()
{
//You can change the state here
StockMarket s = new StockMarket();
s.Companies.Add(new Company(this.GetType(), "aa", "_", 123, 1234));
return s;
}
//...
}
Now you cannot change the state here:
public partial class Observer: Form
{
private StockMarket stockMarket;
public ConcreteObserverPull()
{
InitializeComponent();
stockMarket = new StockMarket();
//Here you cannot change the state
stockMarket.Companies.Add(new Company(this.GetType(), "aa", "_", 123,12));
}
//...
}
Sorry, I don't know C#, but as an idea, you can wrap returned entities with decorator or proxy, which will throw an exception in case of trying to modify state of a company.
Returning clones with fields set as readonly is the safest way to go.

Form sending data to another form

I'm currently trying to make a form that sends 2 class, then receives the data, uses them but want to shoot them back to the original form. Any idea on how I could?
This is when i call my second form:
var tmp = new Pjeu(P1,P2);
tmp.Show();
P are Players. Here's the class:
//---
public class Player
{
public string Name;
public int pts1;
public int pts2;
public int num;
};
And I receive the data like this:
label3.Text = P1.Name;
label5.Text=P2.Name;
I want to use P1.pts or shoot back a number to it. Is it possible the way I do?
You can use multi way:
public class Player
{
public void Pa(string p1,string p2)
{
p1 = Name;
p2 = Name;
}
public string pass1(int ps1)
{
return ps1.ToString();
}
public string pass2(int ps2)
{
return ps2.ToString();
}
public string Name { get; set; }
public int pts1 { get; set; }
public int pts2 { get; set; }
public int num { get; set; }
}
and call:
Player p = new Player();
p.Pa(Label1.Text, Label2.Text);
Label1.Text = p.pts1.ToString();
Label2.Text = p.pts2.ToString();

Start function not being called C#

I get a component like this
GameObject currentAuraObject
IAura currentAura = currentAuraObject.GetComponent<IAura>();
where current aura is
public class AirAura : MonoBehaviour, IAura
{
public ElementalIncreament DamageElementalIncreament { get; set; }
public ElementalIncreament ResistanceElementalIncreament { get; set; }
public ElementalIncreament EnemyElementIncreament { get; set; }
private void Start()
{
DamageElementalIncreament = new ElementalIncreament(ElementalIncreament.ElementalType.Air, 20);
ResistanceElementalIncreament = new ElementalIncreament(ElementalIncreament.ElementalType.Air, 15);
EnemyElementIncreament = new ElementalIncreament(ElementalIncreament.ElementalType.Earth, 35);
}
}
the variable currentAura itself is not null but all the properties are.. I don't understand why the Start function is not being called and initialise the properties properly, how can I fix this ?
To have a function automatically called in your class you need to create a class contructor like below (the function has to be public, have no return type and be the same name as your class):
public AirAura()
{
DamageElementalIncreament = new ElementalIncreament(ElementalIncreament.ElementalType.Air, 20);
ResistanceElementalIncreament = new ElementalIncreament(ElementalIncreament.ElementalType.Air, 15);
EnemyElementIncreament = new ElementalIncreament(ElementalIncreament.ElementalType.Earth, 35);
}

Categories

Resources