Skip to main content

Resources






Please refer to Github link below for latest update on this

https://github.com/ixabhay/UltimateUnityCheatSheet



Backup unity project
https://www.shiftescape.com/2024/07/which-all-files-and-folders-to-backup.html

In order to be able to recreate the Unity Project from a backup zip, just remove Library and Temp folder when backing up the project to a zip file.



What's in there?

- Drawing Board Drag for moving objects while holding them, zooming in using mouse scroll and pinch zoom for touch devices.

- SimpleAES for encrypting and decrypting content.

- Orientation Manager for forcing a certain orientation on Android Devices

- Photon Connect contains a very robust Photon Matchmaking Example using Hashtable for Room Properties and Player Properties.

-SSUpload for taking screenshot of unity screen - flipping the textures and uploading screenshot using REST API.



ULTIMATE UNITY CHEAT SHEET


########################################################
########## for interviewing candidates #################
########################################################

rate your experience with Unity3D out of 10
rate your experience with NodeJS out of 10
rate your experience with SocketIO out of 10

#UNITY {
define PREFABS
unity application life cycle
define inspector tab
in a scene there is a button and a function to be executed and NOTHING ELSE AT ALL
> will it work?
your approach to build a map that follow a particular theme
how would you move an object from position A to B without update, fixed update or late update
teen patti how will you make user look like its sitting at the center of table
photon hash table define
> how will you sync room properties 
> how will you sync player properties
how would you execute a method on Player B's system from Player A's system > photon RPC
}

#NODEJS {
nodejs how would you increase a number each second

define express middle-ware
}

#SOCKETIO {

how to join socket room
> how would you send a message to particular user, given that they have not joined any room explicitly
sending message to particular user

}




########################################################
############  for parsing json from socket #############
########################################################



Debug.Log("Event Name : " + e.name + " Data : " + e.data);

        string recCallBackString = e.data.ToString();

        Debug.Log("recCallback sub string: " + recCallBackString);

        string callBackSubstring = recCallBackString.Substring(1, recCallBackString.Length - 2);

        Debug.Log("Callback sub string: " + callBackSubstring);

        var userListsJSON = sJSON.Parse(callBackSubstring);
foreach(var userName in userListsJSON)
        {
            Debug.Log("Listing user with name: " + userName.ToString());
            Debug.Log("Listing user with name: " + userName.Value);
            shiftLoginManager.GetComponent<ShiftLoginManager>().ListUsersWithName(userName.Value);
        }


########################################################
############  for parsing json from web response ##############
########################################################

// using SimpleJson; JSONNode responseData = sJSON.Parse(www.downloadHandler.text); string loginStatus = responseData["status"].Value; Debug.Log("LoginStatus: " + loginStatus);



########################################################
########## for moving object without Update ############
########################################################



        IEnumerator FakeThrowingCard(Transform target)
        {
            transform.position = dealersDeck.transform.position;

            //  Transform inInitPosition = initPosition.transform;
            //  Transform inTargetPosition = targetPosition.transform;


            //float smoothing = 1.0f;

            while (Vector3.Distance(transform.position, target.position) > 0.05f)
            {

                transform.position = Vector3.Lerp(transform.position, target.position, smoothing * Time.deltaTime);

                yield return null;

            }


            //transform.SetParent(myParentObject.transform);

            // done

            yield return new WaitForSeconds(wfs);

            //finished

        }
########################################################
############### for input to upper case ################
########################################################


        
public InputField inputField;
this goes to start function:

  inputField.onValidateInput += delegate (string input, int charIndex, char addedChar) {
        return nameValidation(addedChar);
  };
and this is the addedChar function that does the control and modification on per character basis:

 private char nameValidation(char c)
 {
     if (c >= 'A' && c <= 'Z') {
         return (char)((int)c - 'A' + 'a');
     }
     else if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == ' ') {
         return c;
     } else {
         return '\0';
     }
 }

no more onChange causing more change!


And here's an even simpler function to force uppercase...

 void Start()
 {
     your_input.onValidateInput += 
         delegate (string s, int i, char c) { return char.ToUpper(c); };
 }
 
And if you want ONLY letters:

 void Start()
 {
     your_input.onValidateInput += delegate (string s, int i, char c) { return char.ToUpper(c); };
 }
 
 char Val(char c)
 {
     c =  char.ToUpper(c);
     return char.IsLetter(c) ? c : '\0';
 }

Here's uppercase letters only, and a length limit:

     your_input.onValidateInput += delegate (string s, int i, char c)
     {
         if (s.Length >= 4) { return '\0'; }
         c = char.ToUpper(c);
         return char.IsLetter(c) ? c : '\0';
     };

(Alternately, don't forget the very handy .CharacterValidation approach. It is often all you need:)

 void Start()
 {
     your_input.characterValidation = InputField.CharacterValidation.Alphanumeric;
 }


So when using .onValidateInput the .Net "char." functions are very handy.




###########################################################
######### for layout bug fixing after adding items at runtime #########
###########################################################

public void InstantReturn()
        {
            transform.SetParent(dealersDeck);

            transform.SetAsLastSibling();

            LayoutRebuilder.ForceRebuildLayoutImmediate(dealersDeck);
        }


//////// UNITY AS A LIBRARY /////////
https://github.com/Unity-Technologies/uaal-example



###########################################################
######### Sending json file to REST API #########
###########################################################

private IEnumerator SavingUserProgressToServer(string fileContents)
{
yield return new WaitForEndOfFrame();

byte[] bArray = Encoding.ASCII.GetBytes(fileContents);


//string enc = Convert.ToBase64String(fileContents);
//string enc = fileContents;


WWWForm form = new WWWForm();



//form.AddField("UserId", PlayerPrefs.GetString("userid"));

//form.AddField("userid", "42");
form.AddField("UserId", 42);

//Debug.Log("Getting file at: " + saveFilePath);

Debug.Log("File contents: " + fileContents);

//form.AddField("file", fileContents);

form.AddBinaryData("files", bArray, "game_manager.json","application/json");


//UnityWebRequest www = UnityWebRequest.Post("localhost:3001/upload", form);
UnityWebRequest www = UnityWebRequest.Post("localhost:3000/SaveJsonFileApi", form);

//www.certificateHandler = new BypassCertificate();

yield return www.SendWebRequest();
print("Upload Files ");
if (www.isHttpError || www.isNetworkError)
{
Debug.Log(www.error);

Debug.Log("Uploaded " + " Failed");
}
else
{
Debug.Log("Uploaded " + " files Successfully");

}


}


public class BypassCertificate : CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
return true;
}
}



###########################################################
######### Reading data from REST API using SimpleJSON #########
###########################################################


IEnumerator FetchProductsNow()
    {
        yield return new WaitForEndOfFrame();

        UnityWebRequest www = UnityWebRequest.Get("https://shiftescape.com/api/Offer/GetHomePageOffers?StoreId=3");

        yield return www.SendWebRequest();

        if(www.isHttpError || www.isNetworkError)
        {
            Debug.Log(www.error);
        }
        else
        {
           // Debug.Log(www.downloadHandler.text);
            JSONNode itemsData = sJSON.Parse(www.downloadHandler.text);

            totalProductsCount = itemsData["ResponseMessage"][1].Count;

            Debug.Log("Some item: " + itemsData["ResponseMessage"][1][3]["ItemName"]);

            for(int i = 0; i < totalProductsCount; i++)
            {
                if(i < productPlaceholders.Length)
                {

                    productPlaceholders[i].TextureURL = itemsData["ResponseMessage"][1][i]["ItemPhoto"];
                    productPlaceholders[i].productName = itemsData["ResponseMessage"][1][i]["ItemName"];
                    productPlaceholders[i].productPrice = itemsData["ResponseMessage"][1][i]["SellingPrice"];
                    productPlaceholders[i].RefreshProduct();
                }
            }
        }

    }


Comments

Popular posts from this blog

Unity Mobile Game Optimization Checklist

- On Image and Text components that aren’t interacted with you can uncheck “Raycast Target” on it, as it will remove them from any Raycast calculus. - Click on your textures in your “Project” window. Click on the “Advanced” arrow, and now check “Generate Mip Maps”, Unity especially recommends it for faster texture loading time and a lower rendering time. - Set the “Shadow Cascades” to “No Cascades” (Quality settings) - If you have dynamic UI elements like a Scroll Rect with a lot of elements to visualize, a good practice is to turn off the pixel perfect check box on the canvas that contains the list and disable the items that aren’t visible on the screen. - Set all non moving objects to "Static" - Above Unity3d 2017.2 you should turn off "autoSyncTransforms" on the Physics tab - Always use Crunch Compression Low on textures - Try to keep the “Collision Detection Mode” on “Discrete” if possible, as “Dynamic” demands more performance. - You can go to the TimeManager w...

How to make RPC in Unreal Engine Steam Online Subsystem and EOS

Remote Procedure Calls, also known as RPCs, are a way to call something on any other instance.  In the Unreal Engine, RPCs are used to ship events from the patron to the server, the server to the customer, or from the server to a specific group. It's important to word that RPCs cannot have a return cost. If you want to return something, you'll ought to use a seconds RPC within the contrary path. There are precise policies that RPCs observe, which are unique in the official Documentation. Some of these regulations encompass wherein the RPC must be run, such as the server instance of an Actor, on the owner of the Actor, or on all instances of the Actor. There are some necessities for RPCs. First, they must be referred to as on Actors or replicated Subobjects. The Actor (and component) have to additionally be replicated. If the server is looking an RPC to be executed on a customer, handiest the patron who owns that Actor will execute the function. Similarly, if a client is calling...

How to drag and drop item in Unity3D

  For dragging and dropping to work we will need to first grab the Game Object and ensure while the Game Object remains grabbed it's position reciprocates the mouse position. This will work fine for not only PC bug mobile devices as well. First define GameObject which we will be dragging. public GameObject selectedPiece; Now inside Update method we will give reference to touched/clicked object and while there is a reference available to an game object(selectedPiece;) we will move that object to mouse position. When the reference is remove, object won't move therefore dropped. void Update(){ RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); if (Input.GetMouseButtonDown(0)){ if(hit.transform != null)             {                 if (hit.transform.CompareTag("PIECE"))                 {     ...