Starting Animation from random time frame Unity

Code snippet to start the animation at different time. Useful when there are many same animation running on screen and you want to make them random.

Animator anim = GetComponent<Animator> ();
AnimatorStateInfo state = anim.GetCurrentAnimatorStateInfo (0);
anim.Play (state.fullPathHash, -1, Random.Range(0f,1f));

You can add this code in Start or Awake function and add to the GameObject with the Animator component.

C# code to shuffle Array

private T[] ShuffleArray<T>(T[] array) {
    System.Random r = new System.Random ();
    for(int i = array.Length; i > 0; i--) {
        int j = r.Next (i);
        T k = array [j];
        array [j] = array [i - 1];
        array [i - 1] = k;
    }

    return array;
}

Example:

Int Array

int[] intArray = new int[] {1,2,3,4};

intArray = ShuffleArray(intArray);

Float Array

float[] floatArray = new float[] {1.0f,2.0f,3.0f,4.0f};

floatArray = ShuffleArray(floatArray);

Invisible Transparent Button in Unity3D

Today i was working on a project where i required to add the invisible button. I tried different methods like making button transparent, adding the image in the button. But then i came to know about this solution. I think that this is probably the best solution.

Steps to add invisible button in Unity3D

1. Add the Button. (UI -> Button)
2. Edit the height and width of the button according to your fit.
3. Delete the Image(Script) and the text from the button.
4. Create new C# script (Touchable.cs) and add the following code into it:


// Touchable.cs
using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(Touchable))]
public class Touchable_Editor : Editor
{ public override void OnInspectorGUI(){} }
#endif
public class Touchable:Text
{ protected override void Awake() { base.Awake();} }

5. Add Touchable.cs script to the button.

Done!

Now you have the invisible button.

Source: UnityForum