This post provides a handy reference guide to go from Scratch’s “Control” category of code blocks to C# with Unity.
Code Blocks
Click on the picture of any of these Scratch code blocks to see how to write similar code statements in C#.
[csharp]
IEnumerator Start()
{
// Optional code here
yield return new WaitForSeconds(1f);
// Optional code here
}
[/csharp]
[csharp]
for (int i = 0; i < 10; ++i)
{
// Code to repeat
}
[/csharp]
You can simply use the “Update” method of a “MonoBehaviour”:
[csharp]
void Update()
{
// Code to repeat per frame
}
[/csharp]
Or, you can use a “while” loop. Make sure to provide some way to pause execution (like a yield statement in a Coroutine) or you will lock up Unity.
[csharp]
IEnumerator Start()
{
while(true)
{
// Optional code here
yield return null; // wait a frame
// Optional code here
}
}
[/csharp]
[csharp]
// “condition” is anything that evaluates to true or false
if (condition)
{
// Code to execute when condition is true
}
[/csharp]
[csharp]
// “condition” is anything that evaluates to true or false
if (condition)
{
// Code to execute when condition is true
}
else
{
// Code to execute when condition is false
}
[/csharp]
[csharp]
// Optional code here
// “condition” is anything that evaluates to true or false
yield return new WaitUntil(() => condition);
// Optional code here
[/csharp]
This is basically a “while” loop where you want the condition to be false:
[csharp]
// “condition” is anything that evaluates to true or false
while (!condition)
{
// Code to repeat
}
[/csharp]
You can stop a script by disabling it.
[csharp]
enabled = false;
[/csharp]
Or, if you were running a Coroutine you could stop it:
[csharp]
var coroutine = SomeCoroutine();
StartCoroutine(coroutine);
StopCoroutine(coroutine);
[/csharp]
There isn’t a “good” equivalent for this, but a possible solution exists based on a pattern Unity has implemented. Whenever a clone is instantiated, the name of the clone will have “(Clone)” added to the end of its name. I only say it isn’t a “good” solution because you can rename an instantiated clone and then wouldn’t have any way to determine that status.
[csharp]
void Start()
{
if (name.Contains(“Clone”))
{
Debug.Log(“I’m a clone!”);
}
}
[/csharp]
[csharp]
Instantiate(gameObject);
[/csharp]
[csharp]
Destroy(gameObject);
[/csharp]
Summary
This should cover all of the code blocks in Scratch’s “Control” category. If you have any questions about this reference guide feel free to ask below.
If you find value in my blog, you can support its continued development by becoming my patron. Visit my Patreon page here. Thanks!