Android Get the next or previous Enum - android

I need a way to get the next/previous enum.
My problem is that I cannot iterate the normal way:
for( Mode m: Mode.values() ) {
. . .
}
I need to get the next enum inside a method, each time it is called:
Note that Mode is a system Enum, therefore I cannot define methods, unless I create my own Enum, which is a solution, but a less preferred one.
public class A {
private Mode m;
A() {
m = Mode.CLEAR;
}
...
protected onClick(View v) {
...
v.getBackground().SetColorFilter(R.color.azure, m);
m = m.next(); // <-- I need something like this
...
}

//Store these somewhere in your class
Mode[] modes = Mode.values();
int modeCount = modes.length;
protected void onClick(View v) {
//Get the next mode, wrapping around if you reach the end
int nextModeOrdinal = (m.ordinal() + 1) % modeCount;
m = modes[nextModeOrdinal];
}
For Kotlin, you can declare an extension function on all enum types that would allow you to define a next() function on all enum instances:
/**
* Returns the next enum value as declared in the class. If this is the last enum declared,
this will wrap around to return the first declared enum.
*
* #param values an optional array of enum values to be used; this can be used in order to
* cache access to the values() array of the enum type and reduce allocations if this is
* called frequently.
*/
inline fun <reified T : Enum<T>> Enum<T>.next(values: Array<T> = enumValues()) =
values[(ordinal + 1) % values.size]
Then you can have something like:
enum class MyEnum {
ONE, TWO, THREE
}
Then you can just use val two = MyEnum.ONE.next()

Implement this method:
public static Mode nextMode(Mode mode) {
return (mode.ordinal() < Mode.values().length - 1) ? Mode.values()[mode.ordinal() + 1] : null;
}

Related

Connecting two objects from different scenes in Unity [duplicate]

How can I pass score value from one scene to another?
I've tried the following:
Scene one:
void Start () {
score = 0;
updateScoreView ();
StartCoroutine (DelayLoadlevel(20));
}
public void updateScoreView(){
score_text.text = "The Score: "+ score;
}
public void AddNewScore(int NewscoreValue){
score = score + NewscoreValue;
updateScoreView ();
}
IEnumerator DelayLoadlevel(float seconds){
yield return new WaitForSeconds(10);
secondsLeft = seconds;
loadingStart = true;
do {
yield return new WaitForSeconds(1);
} while(--secondsLeft >0);
// here I should store my last score before move to level two
PlayerPrefs.SetInt ("player_score", score);
Application.LoadLevel (2);
}
Scene two:
public Text score_text;
private int old_score;
// Use this for initialization
void Start () {
old_score = PlayerPrefs.GetInt ("player_score");
score_text.text = "new score" + old_score.ToString ();
}
but nothing displayed on screen, and there's no error.
Is this the correct way to pass data ?
I am using Unity 5 free edition, develop game for Gear VR (meaning the game will run in android devices).
Any suggestion?
There are many ways to do this but the solution to this depends on the type of data you want to pass between scenes. Components/Scripts and GameObjects are destroyed when new scene is loaded and even when marked as static.
In this answer you can find
Use the static keyword
Use DontDestroyOnLoad
Store the data local
3a PlayerPrefs
3b serialize to XML/JSON/Binary and use FileIO
1. Use the static keyword.
Use this method if the variable to pass to the next scene is not a component, does not inherit from MonoBehaviour and is not a GameObject then make the variable to be static.
Built-in primitive data types such as int, bool, string, float, double. All those variables can be made a static variable.
Example of built-in primitive data types that can be marked as static:
static int counter = 0;
static bool enableAudio = 0;
static float timer = 100;
These should work without problems.
Example of Objects that can be marked as static:
public class MyTestScriptNoMonoBehaviour
{
}
then
static MyTestScriptNoMonoBehaviour testScriptNoMono;
void Start()
{
testScriptNoMono = new MyTestScriptNoMonoBehaviour();
}
Notice that the class does not inherit from MonoBehaviour. This should work.
Example of Objects that cannot be marked as static:
Anything that inherits from Object, Component or GameObject will not work.
1A.Anything that inherits from MonoBehaviour
public class MyTestScript : MonoBehaviour
{
}
then
static MyTestScript testScript;
void Start()
{
testScript = gameObject.AddComponent<MyTestScript>();
}
This will not work because it inherits from MonoBehaviour.
1B.All GameObject:
static GameObject obj;
void Start()
{
obj = new GameObject("My Object");
}
This will not work either because it is a GameObject and GameObject inherit from an Object.
Unity will always destroy its Object even if they are declared with the static keyword.
See #2 for a workaround.
2.Use the DontDestroyOnLoad function.
You only need to use this if the data to keep or pass to the next scene inherits from Object, Component or is a GameObject. This solves the problem described in 1A and 1B.
You can use it to make this GameObject not to destroy when scene unloads:
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
You can even use it with the static keyword solve problem from 1A and 1B:
public class MyTestScript : MonoBehaviour
{
}
then
static MyTestScript testScript;
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
void Start()
{
testScript = gameObject.AddComponent<MyTestScript>();
}
The testScript variable will now be preserved when new scene loads.
3.Save to local storage then load during next scene.
This method should be used when this is a game data that must be preserved when the game is closed and reopened. Example of this is the player high-score, the game settings such as music volume, objects locations, joystick profile data and so on.
Thare are two ways to save this:
3A.Use the PlayerPrefs API.
Use if you have just few variables to save. Let's say player score:
int playerScore = 80;
And we want to save playerScore:
Save the score in the OnDisable function
void OnDisable()
{
PlayerPrefs.SetInt("score", playerScore);
}
Load it in the OnEnable function
void OnEnable()
{
playerScore = PlayerPrefs.GetInt("score");
}
3B.Serialize the data to json, xml or binaray form then save using one of the C# file API such as File.WriteAllBytes and File.ReadAllBytes to save and load files.
Use this method if there are many variables to save.
General, you need to create a class that does not inherit from MonoBehaviour. This class you should use to hold your game data so that in can be easily serialized or de-serialized.
Example of data to save:
[Serializable]
public class PlayerInfo
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int life = 0;
public float highScore = 0;
}
Grab the DataSaver class which is a wrapper over File.WriteAllBytes and File.ReadAllBytes that makes saving data easier from this post.
Create new instance:
PlayerInfo saveData = new PlayerInfo();
saveData.life = 99;
saveData.highScore = 40;
Save data from PlayerInfo to a file named "players":
DataSaver.saveData(saveData, "players");
Load data from a file named "players":
PlayerInfo loadedData = DataSaver.loadData<PlayerInfo>("players");
There is another way:
ScriptableObject
ScriptableObjects are basically data containers but may also implement own logic. They "live" only in the Assets like prefabs. They can not be used to store data permanently, but they store the data during one session so they can be used to share data and references between Scenes ... and - something I also often needed - between Scenes and an AnimatorController!
Script
First you need a script similar to MonoBehaviours. A simple example of a ScriptableObject might look like
// fileName is the default name when creating a new Instance
// menuName is where to find it in the context menu of Create
[CreateAssetMenu(fileName = "Data", menuName = "Examples/ExamoleScriptableObject")]
public class ExampleScriptableObject : ScriptableObject
{
public string someStringValue = "";
public CustomDataClass someCustomData = null;
public Transform someTransformReference = null;
// Could also implement some methods to set/read data,
// do stuff with the data like parsing between types, fileIO etc
// Especially ScriptableObjects also implement OnEnable and Awake
// so you could still fill them with permanent data via FileIO at the beginning of your app and store the data via FileIO in OnDestroy !!
}
// If you want the data to be stored permanently in the editor
// and e.g. set it via the Inspector
// your types need to be Serializable!
//
// I intentionally used a non-serializable class here to show that also
// non Serializable types can be passed between scenes
public class CustomDataClass
{
public int example;
public Vector3 custom;
public Dictionary<int, byte[]> data;
}
Create Instances
You can create instances of ScriptableObject either via script
var scriptableObject = ScriptableObject.CreateInstance<ExampleScriptableObject>();
or to make things easier use the [CreateAssetMenu] as shown in the example above.
As this created ScriptabeObject instance lives in the Assets it is not bound to a scene and can therefore be referenced everywhere!
This when you want to share the data between two Scenes or also e.g. the Scene and an AnimatorController all you need to do is reference this ScriptableObject instance in both.
Fill Data
I often use e.g. one component to fill the data like
public class ExampleWriter : MonoBehaviour
{
// Here you drag in the ScriptableObject instance via the Inspector in Unity
[SerializeField] private ExampleScriptableObject example;
public void StoreData(string someString, int someInt, Vector3 someVector, List<byte[]> someDatas)
{
example.someStringValue = someString;
example.someCustomData = new CustomDataClass
{
example = someInt;
custom = someVector;
data = new Dictionary<int, byte[]>();
};
for(var i = 0; i < someDatas.Count; i++)
{
example.someCustomData.data.Add(i, someDatas[i]);
}
example.someTransformReference = transform;
}
}
Consume Data
So after you have written and stored your required data into this ExampleScriptableObject instance every other class in any Scene or AnimatorController or also other ScriptableObjects can read this data on just the same way:
public class ExmpleConsumer : MonoBehaviour
{
// Here you drag in the same ScriptableObject instance via the Inspector in Unity
[SerializeField] private ExampleScriptableObject example;
public void ExampleLog()
{
Debug.Log($"string: {example.someString}", this);
Debug.Log($"int: {example.someCustomData.example}", this);
Debug.Log($"vector: {example.someCustomData.custom}", this);
Debug.Log($"data: There are {example.someCustomData.data.Count} entries in data.", this);
Debug.Log($"The data writer {example.someTransformReference.name} is at position {example.someTransformReference.position}", this);
}
}
Persistence
As said the changes in a ScriptableObject itself are only in the Unity Editor really persistent.
In a build they are only persistent during the same session.
Therefore if needed I often combine the session persistence with some FileIO (as described in this answer's section 3b) for loading and deserializing the values once at session begin (or whenever needed) from the hard drive and serialize and store them to a file once on session end (OnApplicationQuit) or whenever needed.
(This won't work with references of course.)
Besides playerPrefs another dirty way is to preserve an object during level loading by calling DontDestroyOnLoad on it.
DontDestroyOnLoad (transform.gameObject);
Any script attached to the game object will survive and so will the variables in the script.
The DontDestroyOnLoad function is generally used to preserve an entire GameObject, including the components attached to it, and any child objects it has in the hierarchy.
You could create an empty GameObject, and place only the script containing the variables you want preserved on it.
I use a functional approach I call Stateless Scenes.
using UnityEngine;
public class MySceneBehaviour: MonoBehaviour {
private static MySceneParams loadSceneRegister = null;
public MySceneParams sceneParams;
public static void loadMyScene(MySceneParams sceneParams, System.Action<MySceneOutcome> callback) {
MySceneBehaviour.loadSceneRegister = sceneParams;
sceneParams.callback = callback;
UnityEngine.SceneManagement.SceneManager.LoadScene("MyScene");
}
public void Awake() {
if (loadSceneRegister != null) sceneParams = loadSceneRegister;
loadSceneRegister = null; // the register has served its purpose, clear the state
}
public void endScene (MySceneOutcome outcome) {
if (sceneParams.callback != null) sceneParams.callback(outcome);
sceneParams.callback = null; // Protect against double calling;
}
}
[System.Serializable]
public class MySceneParams {
public System.Action<MySceneOutcome> callback;
// + inputs of the scene
}
public class MySceneOutcome {
// + outputs of the scene
}
You can keep global state in the caller's scope, so scene inputs and outputs states can be minimized (makes testing easy). To use it you can use anonymous functions:-
MyBigGameServices services ...
MyBigGameState bigState ...
Splash.loadScene(bigState.player.name, () => {
FirstLevel.loadScene(bigState.player, (firstLevelResult) => {
// do something else
services.savePlayer(firstLevelResult);
})
)}
More info at https://corepox.net/devlog/unity-pattern:-stateless-scenes
There are various way, but assuming that you have to pass just some basic data, you can create a singelton instance of a GameController and use that class to store the data.
and, of course DontDestroyOnLoad is mandatory!
public class GameControl : MonoBehaviour
{
//Static reference
public static GameControl control;
//Data to persist
public float health;
public float experience;
void Awake()
{
//Let the gameobject persist over the scenes
DontDestroyOnLoad(gameObject);
//Check if the control instance is null
if (control == null)
{
//This instance becomes the single instance available
control = this;
}
//Otherwise check if the control instance is not this one
else if (control != this)
{
//In case there is a different instance destroy this one.
Destroy(gameObject);
}
}
Here is the full tutorial with some other example.
you have several options.
The first one I see is to use static variables, which you will not lose their information or value passing from scenes to scenes (since they are not bound to the object). [you lose the information when closing the game, but not when passing between scenes]
the second option is that the player or the object of which you do not want to lose the information, you pass it through the DontDestroyOnLoad function
Here I give you the documentation and the sample code. [You lose the information when you close the game, but not when you go between scenes]
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
Third is to use the playerPrefab [https://docs.unity3d.com/ScriptReference/PlayerPrefs.html]
that allow you to save information and retrieve it at any time without hanging it even after closing the game [you must be very careful with the latter if you plan to use it to save data even after closing the game since you can lose the data if you close the game suddenly , since player prefab creates a file and retrieves the information from there, but it saves the file at the end or closes the app correctly]

Mockito - Set default return string value for all mocked methods

I have a class that has over 20 methods that return string values. These strings are not relevant for my test, but it's pretty time consuming to set a when->thenReturn case for each of the functions, specially because there are several of these classes.
Is there a way to tell mockito to default empty string instead of null, or any string value that I wish for that matter?
I created a class to perform this on your project whenever needed, simply init the mock (usually in #Before function)
myClassMock = mock(MyClass::class.java, NonNullStringAnswer())
NonNullStringAnswer.kt
/** Used to return a non-null string for class mocks.
*
* When the method called in the Mock will return a String, it will return the name of the
* method instead of null.
*
* For all other methods the default mocking value will be returned.
*
* If you want to mock additional methods, it is recommended to use doReturn().when instead on
* when().thenReturn
*
* Example of usage:
*
* myClassMock = mock(MyClass::class.java, NonNullStringAnswer())
*
**/
class NonNullStringAnswer : Answer<Any> {
#Throws(Throwable::class)
override fun answer(invocation: InvocationOnMock): Any {
return if (invocation.method.returnType == String::class.java) {
invocation.toString()
} else {
Mockito.RETURNS_DEFAULTS.answer(invocation)
}
}
}

Android Passing Variable doesn't seem to click

I have created a random number and would like to pass it along to use in the same file just different class. Please help:
public void Start() {
int number = random.nextInt(3); // Gives a number such that 0 <= number < 2
then a few lines down I try to use number but it's telling me it's not a variable to use:
public void renderBackground(Canvas canvas) {
//TODO: you may wish to change background colors from here
if(number=="0") {
any kind of help is great appreciated!
The problem you are facing is because of the scope of variable number. I'm not sure you are using inner class or a separate class.
If it's a inner class, then declare the number at top of the first class like,
class Firstclass
{
public int number; // scope is public it can be accessed anywhere in class
method();
...
...
class Secondclass
{
method()
{
System.out.println("Your number is : " + number); // here you are accessing variable `number`
}
}
}
Also, try to change
if(number=="0") {
to
if(number==0) {
I think the problem is you are initializing 'number' inside a class, not the main class.
initialize number inside the main class then modify it in your method. ex:

Translating iOS Enums to Android

I'm busy trying to translate some iOS code to Android code. The iOS code contains Enums, like the following:
typedef NS_OPTIONS(NSUInteger, Traits) {
TraitNumberOne = 1<<0,
TraitNumberTwo = 1<<1,
);
I have never worked with Enums before in Android, and am having trouble interpreting the documentation and examples that are available. How would I translate the above example to Android code?
use this
public enum NS_OPTIONS {
TraitNumberOne (1<<0),
TraitNumberTwo (1<<1);
private final int Option;
public int getOption()
{
return Option;
}
private NS_OPTIONS(int option) {
this.Option= option;
}
}
Use it like this:
int value = NsOptions.TraitNumberOne.getOption();
Java enums are relatively simple, but can be made more complex to fit whatever needs you want to use them for. If you just want the type-safety of an enum, you can just declare the variable names like this:
public enum Traits{
TraitNumberOne,
TraitNumberTwo
}
If you want more advanced features of an enum, it's treated exactly like a class that is instantiated statically for each item in the enum. So, you can have a constructor and input whatever value you want associated with each individual item, like so:
public enum Traits{
TraitNumberOne(0x01),
TraitNumberTwo(0x02),
// future items go here
; // don't forget the semi-colon, which indicates the list of items is ending
// now, create a private variable to store the data
private final int data;
// and the constructor to set the data
private NsOptions(int data){
this.data = data;
}
// now, you can provide an accessor to provide access to the data
public int getData(){
return this.data;
}
}
You can use the above enum like this:
Traits currentOptions = Traits.TraitNumberOne;
int optionsData = currentOptions.getData();
The idea of NS_OPTIONS is to allow all possible combinations of the enumerated values to be represented by one value (this is why bitwise operators are used). In Java, I guess the equivalent would be:
public enum Permission {
TraitNumberOne (0b01),
TraitNumberTwo (0b10);
...
}
We can implement in android like ,
public enum NS_OPTIONS{
TraitNumberOne(1),TraitNumberTwo(2);
private int type;
NS_OPTIONS(int type){
this.type = type;
}
public int getType(){
return type;
}
}
and if you want to use above enum from your class you can use it like,
int i =NS_OPTIONS.TraitNumberOne;//which will return 1
int j =NS_OPTIONS.TraitNumberTwo;//which will return 2;

Android - can you have multiple variable types for single method() parameter?

Can you have two or more variable types for a single method() parameter?
At the moment, you can do:
method(String string, int int, etc...) {
}
What if you wanted to do something like
method(String or int stringint) {
}
can this be done?
I'd do it like this:
private boolean function(String str){
// Do stuff
}
private boolean function(int intStr){
String str = convertToString(intStr);
return function(str);
}
Avoids unnecessary classes, etc.
Just overload the method signature.
public void someMethod(string argument){
}
public void someMethod(int argument){
}
If you have to stick to one single parameter you can use a wrapper, which contains two fiels:
public class MyWrapper
{
String stringValue;
int intValue;
}
public void someMethod(MyWrapper arg)
{
if(arg.stringField != null)
{
// do something with the string
}
/* checking for the default value 0 makes no sense here, since it
might be a value you actually want to pass - The first conditional
statement covers the case you actually only passed a string
*/
else
{
// do something with the int
}
}

Categories

Resources