if (GetComponentInChildren<tk2dSprite>() == null) { var sprite = GetComponentInChildren<tk2dSlicedSprite>(); } else { var sprite = GetComponentInChildren<tk2dSprite>(); } //Вот начиная отсюда, sprite подкрашиваться красным. (does not exist) var joyWorldTopRight = sprite.transform.TransformPoint(sprite.GetBounds().max); var joyScreenTopRight = BattleGUI.Instance.GuiCamera.WorldToScreenPoint(joyWorldTopRight); var joyWorldBottomLeft = sprite.transform.TransformPoint(sprite.GetBounds().min); var joyScreenBottomLeft = BattleGUI.Instance.GuiCamera.WorldToScreenPoint(joyWorldBottomLeft); 

Of course, the entire lower part of the code can be put into a separate method, or it can simply be duplicated - something is not particularly good, dubbing the code and an extra method call on level ground. Are there alternatives?

  • one
    To declare before the if condition the variable dynamiс sprite not an option? - Alexey Shimansky
  • one
    You can, if they inherit from one class (or implement one interface) or, for example, tk2dSlicedSprite inherits from tk2dSprite - eastwing
  • one
    or, in extreme cases, sprite can be of type object or even dynamic (in the latter case, you need to keep track of performance, but you don’t need to do type conversions) - eastwing
  • one
    @Dmitrii dynamic is the type of the C # language in which you actually write - Alexey Shimansky
  • one
    Oh, exactly, in the same Mono 2.0. Was wrong, I apologize - eastwing Nov.

1 answer 1

First of all, in your example, the variable — more precisely, the variablessprite exists only inside the processing condition. Of course, outside of it, work with variables is impossible.

Since components belong to different types, it is necessary to “climb” through levels of abstractions until a common class or interface is found for the components.

According to the documentation (it’s about the Toolkit2D asset?), The sprites in the toolkit inherit from the tk2dBaseSprite class, respectively, you need to do something like this:

 tk2dBaseSprite sprite; if (GetComponentInChildren<tk2dSprite>() == null) { sprite = (tk2dSlicedSprite) GetComponentInChildren<tk2dSlicedSprite>(); } else { sprite = (tk2dSprite) GetComponentInChildren<tk2dSprite>(); } 
  • one
    Ahead with the correct answer) +1. - BlackWitcher