Unity borking values when using Instantiate()?

I have set up the following class:
public class PlayerBall : MonoBehaviour {
public int x = 3;
void Awake() {
x = 2;
Debug.Log(a);
}
void setX(int y) {
x = y;
Debug.Log(x);
}
void Start() {
Debug.Log(x);
}
}

If in another script you Instantiate this object correctly, then call GetComponent().setX(1) I get the following output:
2
1
2

Which makes no sense. It is as if Unity decides to set things back to how they were when awake was called. In my project, I am assigning a composed member object where I would use setX. How can this be fixed?

According to the Unity manual’s entry about Execution Order - Unity - Manual: Order of execution for event functions - when you Instantiate the object, it should run Awake(), then Start(), and then when you call setX(1), that should run, so you’re right, I’d expect the output to be 2 (From Awake), 2 (From Start) and then 1 (From setX).

Are you sure you are called the correct setX()? Your code above shows that your setX() is not public, so calling it from another class is not possible.

From my tests using your code, it seems setX() is being called before Start() is called. If I delay the calling of setX(), by putting it in an OnTriggerEnter() for instance, then it definitely is as per the Execution Order, first Awake(), then Start(), then the setX().

Also, please check your code, you have an ‘a’ instead of an ‘x’ in your Awake() Debug.Log:
Debug.Log(a);