-1

So here is my code,

public void CheckStatChal()      
{
    foreach (SpotUIBase menu in thisSpot.ownMenus)
    {
        if (menu.uiSort == SpotUISort.StatEvent)
        {
            if(menu != null)
                Debug.Log("Menu name is "+menu.Name);
            var statEvent = menu as StatEvent;
            if (statEvent == null)
            {
                Debug.Log("Stat event is null, name is "+thisSpot.Name);
                continue;
            }
            .......... [1]

public SpecialSpotClass thisSpot; 
public abstract class SpecialSpotClass 
{  
 public List<SpotUIBase> ownMenus = new List<SpotUIBase>();  
 ....
public  class SpotUIBase
{
  public SpotUISort uiSort;
   ....
public class StatEvent : SpotUIBase
{
   ....
public enum SpotUISort{
   Inn, Shop, Bar,  

I am using Unity engine now. So if run this code, I got Debug.Log("Menu name is "+menu.Name); and Debug.Log("Stat event is null, name is "+thisSpot.Name); both. Why? menu is not null, but after downcast it, it become null? I don't understand this why.

So in this code, I want to execute [1] part below codes, but [statEvent] is null, so all the code below does not called by (continue keyword)

Why downcast become null?

Help please.

creator
  • 671
  • 11
  • 28
  • It is null because menu is not a `StatEvent` it is a `SpotUIBase` and, as far as your code shows, a `SpotUIBase` doesn't extend or implement any other class or interface. Are you trying to cast `menu.uiSort` to a `StatEvent`? – Lithium Apr 27 '17 at 12:47
  • you have your null checks wrong. You are accesing `menu.uiSort` before checking if it is null `if(menu != null) Debug.Log("Menu name is "+menu.Name);`. – Cleptus Apr 27 '17 at 12:49
  • So StatEvent is inherited from SpotUIBase.. public class StatEvent : SpotUIBase { – creator Apr 27 '17 at 12:50
  • I agree with @Lithium. Based on the information we have, `statEvent` will always be null unless you do `menu as SpotUIBase` – KSib Apr 27 '17 at 16:36

1 Answers1

0

So I googled and confirmed right Downcast method, and changed foreach to for syntax. And solved.

Here is changed code.

for (int i = 0; i < thisSpot.ownMenus.Count; i++)
    {
        if (thisSpot.ownMenus[i].uiSort == SpotUISort.StatEvent)
        {
            thisSpot.ownMenus[i] = SpotUI.Instance.StatEvent;
            var ownMenu = (StatEvent) thisSpot.ownMenus[i];
            Debug.Log("own menu is "+ownMenu.Name);
            if ((!ownMenu.StatChal1.nowCoolTime && ownMenu.StatChal1 != null)
                                             || ownMenu.StatChal1 == null)
            {
                StatChallenge.Instance.MakeStatChal(this, ref ownMenu.StatChal1);
                Debug.Log(ownMenu.StatChal1.Name);
                ownMenu.SetChalInfo(ownMenu.StatChal1, 1);
                chal1 = ownMenu.StatChal1;
            }
creator
  • 671
  • 11
  • 28