Cannot access array of a custom class - unity3d

In unity I keep getting the error message "NullReferenceException: Object reference not set to an instance of an object" on this:
listOfBanks[0].Deposit(50);
and
accntBlnce.text = "Account Balance:\n" + listOfBanks[curBank].GetBalance().ToString("c");
I have 3 options listed in the drop down menu and when I Debug.Log the number of items in the array I get 3 as my count. But I can't do anything with them. The banks variable is set as the Dropdown object in the inspector as well as the accntBlnce as the text object in my panel.
The code is below.
Banks.cs
public class Banks : MonoBehaviour {
public Dropdown banks;
public Text accntBlnce;
public Bank[] listOfBanks;
public int curBank = 0;
void Start() {
listOfBanks = new Bank[banks.options.Count];
listOfBanks[0].Deposit(50);
}
void Update() {
curBank = banks.value;
accntBlnce.text = "Account Balance:\n" + listOfBanks[curBank].GetBalance().ToString("c");
}
}
Bank.cs
public class Bank{
public Bank() { }
public Bank(string orgn, float amntToRprt, float blnce) {
origin = orgn;
amountToReport = amntToRprt;
balance = blnce;
}
public string origin { get; set; }
public float amountToReport { get; set; }
public float balance { get; set; }
public bool Deposit(float amnt) {
if (amnt > 0) {
balance += amnt;
if(amnt > amountToReport) {
FlagForReport();
}
return true;
}
else
return false;
}
private void FlagForReport() {
throw new NotImplementedException();
}
public float GetBalance() {
return balance;
}
public bool Withdraw(float amnt) {
if (amnt > 0) {
if (balance >= amnt) {
balance -= amnt;
return true;
}
else
return false;
}
else
return false;
}
public bool Transfer(float amnt, Bank bank) {
if (amnt > 0) {
if (balance >= amnt) {
if(bank.Deposit(amnt))
balance -= amnt;
return true;
}
else
return false;
}
else
return false;
}
}

This is the fourth time array question is asked this week with the-same problem and the-same solution.
You declared the array here:
listOfBanks = new Bank[banks.options.Count];
but you did not create new instance of each Bank script before calling
listOfBanks[0].Deposit(50); and listOfBanks[curBank].GetBalance().ToString("c").
Declaring array and setting the size is NOT the-same as creating new instance of a script.
The solution is to loop through the array and create new instance of each one.
In your Banks.cs, replace the code in your Start() function with the one below:
void Start()
{
//Declare how much Bank array should be created
listOfBanks = new Bank[banks.options.Count];
//Now Create instance of each bank
for (int i = 0; i < listOfBanks.Length; i++)
{
//Create new instance of each Bank class
//listOfBanks[i] = new Bank();
listOfBanks[i] = new Bank("", 50, 50);
}
listOfBanks[0].Deposit(50);
}

Related

MVVM AsyncExecute causing lag

AsyncExecute method causing lag in my treeview application when I am expanding a branch.
Important parts of my TreeView
public DirectoryItemViewModel(string fullPath, DirectoryItemType type, long size)
{
this.ExpandCommand = new AsyncCommand(Expand, CanExecute);
this.FullPath = fullPath;
this.Type = type;
this.Size = size;
this.ClearChildren();
}
public bool CanExecute()
{
return !isBusy;
}
public IAsyncCommand ExpandCommand { get; set; }
private async Task Expand()
{
isBusy = true;
if (this.Type == DirectoryItemType.File)
{
return;
}
List<Task<long>> tasks = new();
var children = DirectoryStructure.GetDirectoryContents(this.FullPath);
this.Children = new ObservableCollection<DirectoryItemViewModel>(
children.Select(content => new DirectoryItemViewModel(content.FullPath, content.Type, 0)));
//If I delete the remaining part of code in this method everything works fine,
in my idea it should output the folders without lag, and then start calculating their size in other threads, but it first lags for 1-2 sec, then output the content of the folder, and then start calculating.
foreach (var item in children)
{
if (item.Type == DirectoryItemType.Folder)
{
tasks.Add(Task.Run(() => GetDirectorySize(new DirectoryInfo(item.FullPath))));
}
}
var results = await Task.WhenAll(tasks);
for (int i = 0; i < results.Length; i++)
{
Children[i].Size = results[i];
}
isBusy = false;
}
My command Interface and class
public interface IAsyncCommand : ICommand
{
Task ExecuteAsync();
bool CanExecute();
}
public class AsyncCommand : IAsyncCommand
{
public event EventHandler CanExecuteChanged;
private bool _isExecuting;
private readonly Func<Task> _execute;
private readonly Func<bool> _canExecute;
public AsyncCommand(
Func<Task> execute,
Func<bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute()
{
return !_isExecuting && (_canExecute?.Invoke() ?? true);
}
public async Task ExecuteAsync()
{
if (CanExecute())
{
try
{
_isExecuting = true;
await _execute();
}
finally
{
_isExecuting = false;
}
}
RaiseCanExecuteChanged();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
//I suppose that here is the problem cause IDE is hinting me that I am not awaiting here, but I don't know how to change it if it is.
ExecuteAsync();
}
}

how to check if an object is not in the scene

I wanted this code to send a "no" when it doesn't find the object "Player_1" but when it finds it, it sends "yes" in the debug log but when I remove it simply
don't send "no"
{
public GameObject _objeto1;
public GameObject _objeto2;
public float _distancia1;
public
void Start()
{
_distancia1 = 0;
}
void Update()
{
_objeto1 = GameObject.Find("Player_1");
_distancia1 = Vector3.Distance(_objeto1.transform.position, _objeto2.transform.position);
if (_objeto1 == true)
{
Debug.Log("sim");
}
else
{
Debug.Log("nao");
}
}
}
Try this:
public GameObject _objeto1;
public GameObject _objeto2;
public float _distancia1;
void Start()
{
_distancia1 = 0;
}
void Update()
{
_objeto1 = GameObject.Find("Player_1");
if (_object1 != null)
{
_distancia1 = Vector3.Distance(_objeto1.transform.position, _objeto2.transform.position);
}
if (_objeto1 != null)
{
Debug.Log("sim");
}
else
{
Debug.Log("nao");
}
}
Thank you for question!
GameObject.Find() returns GameObject if it's exist on scene and returns "null" when there is no object. So you can use if statment to check if _objeto1 is null.
_objeto1 = GameObject.Find("Player_1");
if (_objeto1 == null)
{
Debug.Log("nao");
}
else
{
Debug.Log("Yes");
}
And don't use '_' for public fields. It's bad practice. You can use it for private fields.

Unity is not showing public methods in the event field 2022

I have 2 mostly identical public methods in the script, but only first one can be shown in the inspector, what happened?
public void playDeadAnim() {
Rigidbody[] allRB = GetComponentsInChildren<Rigidbody>();
for (int r=0;r<allRB.Length;r++) {
allRB[r].isKinematic = false;
}
myAnimator.enabled = false;
}
public void respawnEnemy() {
Rigidbody[] allRB = GetComponentsInChildren<Rigidbody>();
for (int r=0;r<allRB.Length;r++) {
allRB[r].isKinematic = true;
}
myAnimator.enabled = true;
}

DataFlavor in JavaFX not recognized correctly

I'm experiencing a problem when D&D a custom object from Swing to JavaFX and I'm wondering if I'm doing something wrong or its probably a Java FX bug.
My Transferable has been defined as the following:
public class TransferableEmployee implements Transferable {
public static final DataFlavor EMPLOYEE_FLAVOR = new DataFlavor(Employee[].class, "Employee");
public static final DataFlavor DEFINITION_FLAVOR = new DataFlavor(PropertyDefinition[].class, "Definition");
private static final DataFlavor FFLAVORS [] = {EMPLOYEE_FLAVOR, DEFINITION_FLAVOR};
private Employee[] employees;
private PropertyDefinition[] propertyDefinitions;
public MintTransferableEmployee(Employee[] employees, PropertyDefinition[] propertyDefinitions) {
this.employees = employees != null ? employees.clone() : null;
this.propertyDefinitions = propertyDefinitions != null ? propertyDefinitions.clone() : null;
}
public DataFlavor[] getTransferDataFlavors() {
return FFLAVORS.clone();
}
public Object getTransferData(DataFlavor aFlavor) throws UnsupportedFlavorException {
Object returnObject = null;
if (aFlavor.equals(EMPLOYEE_FLAVOR)) {
returnObject = employees;
}
else if(aFlavor.equals(DEFINITION_FLAVOR)){
returnObject = propertyDefinitions;
}
else{
throw new UnsupportedFlavorException(aFlavor);
}
return returnObject;
}
public boolean isDataFlavorSupported(DataFlavor aFlavor) {
boolean lReturnValue = false;
for (int i=0, n=FFLAVORS.length; i<n; i++) {
if (aFlavor.equals(FFLAVORS[i])) {
lReturnValue = true;
break;
}
}
return lReturnValue;
}
}
I've created an imageView (FX Component) where I added the setOnDragOver just as the following:
employeePhotoImageView.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
System.out.println("dragOver");
event.getDragboard().getContentTypes();
event.getDragboard().getContent(DataFormat.lookupMimeType("application/x-java-serialized-object"));
}
});
The getContentTypes() returns a Map with [[application/x-java-serialized-object]], so now I try to get the Content, and this only returns the List of PropertyDefinition but no Employee at all (which in this case, is the one I need).
If I remove the data of the PropertyDefinition in the transferable, the employee is returned in the getContent(DataFormat) method.
For me, this means that JavaFX only works with 1 DataFlavor or somehow it is only returning the last flavor found in the Transferable.
Any clues on this?
Thanks in advanced...

C# IEnumerable Interface

I am trying to understand this example from a MSDN article, to my understanding with the IEnumberable interface, we will be able to use Foreach to loop through the class collection, I am confused at the Main method, why don't we just use:
foreach (Person p in peopleArray)
Console.WriteLine(p.firstName + " " + p.lastName);
instead of
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
Example:
using System;
using System.Collections;
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
You're right, you could simply use the first version because arrays implement IEnumerable.
The reason they chose to iterate over People is simply for academic purposes; to demonstrate how iterators work (and how to implement IEnumerable). If they simply iterated over peoplearray, they wouldn't be using the People class, which is the main focus of that example.