Category Archives: Programming

Missing RectTransform after creating a UI component in script

Sometimes you may create a new UI element in script and want to set it’s position etc.

I wrote a quick extension method to allow me to stretch a newly created component to that of it’s parent:

public static class Extensions
{
	public static void StretchRectTransform(this Transform value)
	{
	    RectTransform rt = value as RectTransform;
	    if (rt == null) return;
	    rt.anchorMin = Vector2.zero;
	    rt.anchorMax = Vector2.one;
	    rt.sizeDelta = Vector2.zero;
	    rt.localScale = Vector3.one;
	}
}

Which I used as follows:

   
public static void Add(GameObject sel)
{
    GameObject go = new GameObject(sel.name+"_HL");
    go.transform.SetParent(sel.transform);
    go.transform.StretchRectTransform();
    image = go.AddComponent<Image>();
}

However I quickly found that the cast of a Transform to a RectTransform did not work in this scenario, as it turns out the RectTransform does not yet exist. I’m not sure when it begins to exist however a quick look at the docs and I noticed it’s a Component so modified my function to add it if it did not exist:

public static void StretchRectTransform(this Transform value)
{
	RectTransform rt = value as RectTransform;
	if (rt == null)
	{
	    rt = value.gameObject.AddComponent<RectTransform>(); // Add a RectTransform if it does not exist
	}
	rt.anchorMin = Vector2.zero;
	rt.anchorMax = Vector2.one;
	rt.sizeDelta = Vector2.zero;
	rt.localScale = Vector3.one;
}

This now works as expected. I assume adding the RectTransform replaces the original Transform, I’ve not found any docs on this so if anyone knows better please share!

Unity3D HingeJoint2D reference angles and setting rotation in script.

This article was born from tracking down an issue (Unity Bug #712007) when setting the rotation of RigidBody2D objects connected with a HingeJoint2D in Unity3D version and 5.1.1p4

I detail how the angle limits work, a potential pitfall when setting rotation on disabled objects and finally detail the spinning issue and a solution we can use until the issue is fixed.

Reference Angle & Joint Limits

It’s important to note that we are using angle constraints where we specify the range of angles the hinge is allowed to be.

TestHinges_2_unity_-_TestHinge2D_-_PC__Mac___Linux_Standalone

Unity does this by first defining a reference angle. You can read the reference angle from the HingeJoint2D but can not set it. So what is it and how is it defined?

First notice that the hinge joint gizmo shows a green line, this is defined by the x axis of the object that the hinge joint is a component of.

TestHinges_2_unity_-_TestHinge2D_-_PC__Mac___Linux_Standalone

 

If we print out HingeJoint2D.referenceAngle for the above we get -17°. Looking at the inspector of the root it has a rotation of -15° and the child a rotation of -32°, so the reference angle is the difference between the rotations of the objects but when?

The simplest answer is it’s when the objects Start would be called, ie the first frame they are active but only then not on subsequent enable / disables.

There is a bit more to it though; the child object must be active when the hinge is enabled. If not, and later  you enable the child, the joint will have no affect on the child until you disable and re-enable the joint or edit other parameters such as motors / limits etc. This may be a bug in Unity, it’s easy to work around though ensure you enable and disable the hinge joint along with the child it connects to.

The unexpected turn

In some scenarios we need to setup the position and rotation of certain bodies. For example setting up a rag-doll to follow on from an animated character, or just initialising a physics model to a pre-recorded settled state. I found that occasionally a certain joint would rotate and end up in an unexpected orientation.

After considerable experimenting I eventually managed to recreate the issue 100% in a simple example. In the below gif both bone hierarchies appear to be the same, looking in the inspector they have the same rotations, angle limits and reference angle.

SpinRotate2

As you can see the right hand hierarchy does not fall as expected, instead it begins to rotate.

To look into this further I displayed the Euler angles followed by Quaternion components for the root and child and you can see that both objects start with the exact same orientations. Looking in the scene view you can see the reference line that Unity draws for the hinge gizmos is within the limits but the second set of bodies decides to rotate round the external part of these limits until it is again within them.

Turn2Now look at the white number inside the root object this is what HingeJoint2D.JointAngle is returning. So for some reason Unity has calculated an angle outside of the 360 degree range and rotates the objects to within the hinge limits.

The setup

As I mentioned the scenario when this occurs in game is when I copy rotations from a RigidBody2D to another in the rag doll. I know the angles are all within the limits already.
In the below test case I have two rag doll setups Source1 and Source2 which appear to be the same in the transform inspector but on printing their quaternions you will note that the quaternion of the source2 root is the negative version of source1. (0.0, 0.0, 0.1, -1.0)

In the video below I first copy source 1 and source 2, if I were to unpause at that stage the copies would do exactly the same as the originals suggesting that the negative quaternion isn’t a problem in it’s self but maybe used during the initialisation of the joint or something.

I then copy the local position and rotation from the orientation objects shown top right. Un-pausing after this then shows up the issue.

You can download the above test project here: TestHinge2D

Initial solution

My initial solution to this was to ensure that all bones in my rag doll had positive w in the quaternion and when I copy the rotations to the rag doll I negate them if necessary to ensure that they too have positive w. This solved my initial problem.

Additional Limbs

During gameplay my character has his left legs and arm disabled since they would be hidden by the right counterparts, it being a 2d side on game. However when the character crashes I enable these limbs and copy the orientation and position from the right parts.

In this scenario ensuring the quaternions had positive w did not solve the issue if the character had been rotating. When that occurs their bodies can gain negative w quaternions, which is no bad thing and I felt from above that what was important was the starting sign.

I’ve not worked out how to fix this occurrence of the issue yet or how to reproduce it in a simple test scene.

 

Unity3D Fatal Error on Startup Workaround

This morning starting up Unity 5.1.0 greeted me with the following message and a blank project selection window (I have unity configured to ask me which project to load on startup)

Fatal error!
GetManagerFromContext: pointer to object of manager ‘(null)’ is NULL (table index 5)

Update

Confirmation from Unity that this is a bug in the updater and they have now disabled this server side checking for versions 5.1.0f3 – 5.1.1f1 so hopefully that’s the last we see of it!

Solution

Many thanks to @Rusty_Bolt on twitter who tweeted to suggest switching WiFi/Internet off which lead me to the following steps. Switching WiFi off would indeed allow unity to start, however after quitting and starting again if WiFi was on (usually is!) it would crash again.

  1. Switch your internet connection off
  2. Load Unity and select a project
  3. Switch your internet connection on
  4. Now within Unity load a new project via File->OpenProject
  5. Quit unity

Hopefully now when you start unity everything is back to normal!

Other things I tried

As part of trying to track this down I tried the following, none of which helped.

  • Delete all unity settings from ~/Library/Preferences
  • Delete my Unity license file from Library/Application Support/PACE Anti-Piracy/License Files see link
  • Moved all of my unity projects to a different location to ensure they were not involved
  • Deleted Unity
  • Installed Unity

Unity3D Canvas Render Order Anomalies

I’m posting this here just so that other’s who experience similar issues know they are not alone and that there is indeed an issue within Unity. (Reported as Issue 707375)

The following occurred in Unity 4.6 and the current 5.1.1f however it did not occur in 5.0. Update: This is now fixed in Unity 5.1.2, thanks Unity!

I’ve spotted in a few different locations in projects that just occasionally, often for a frame or two in an animation a canvas image will flicker. On further inspection it is evident that the item in question gets rendered at the wrong time.

I’ve not been able to determine exactly what causes the issue as usually it’s in quite a complex scene and as soon as I start to edit it the issue goes away. However I have now created a simple test scene which shows up the issue.

Here’s the simple scene a screen space canvas (the bug occurs in other modes too) with red, white and blue Image components being rendered in that order as expected:

Screenshot_062515_011848_PM

Now all I do is add 7 Image components before these and bang the blue image component is now rendered before the white one.

Screenshot_062515_011740_PM

If I add an extra component or delete any of them the bug goes away. Of note the bug does reappear when there are more components in the scene, this scene started off life with 100’s of images in a complex hierarchy and I slowly removed components to get to this simplified version. During this process the sorting order would change but I have not managed to get the issue with anything simpler than this.

You can download this test project here: TestROrder5

I also have another scene which I have not managed to simplify (yet) which has a hierarchy of images which have their scale animated via Unity’s animation system, their active state is not changed and during 2-3 frames of a 50s animation a couple of images render before they should, disappearing behind something.

Unity3D ScriptableObject helper script

If you’ve ever wanted to save some data in Unity that multiple gameobjects need to reference then you should lookup ScriptableObject this is very similar to a GameObject except it does not live in the scene. Instead you create them in your project window and you can then drag them and reference them in GameObjects etc. When selected in the project window you get the usual inspector allowing you to edit them.

In this post I have a small script to simplify this and an example Palette object in just a few lines of code.
Continue reading Unity3D ScriptableObject helper script

Custom popups matching EditorGUILayout.Popup style

So I’m just tidying up one of my editor interfaces and I wanted the button used to pop up a generic menu to match the style used by Unity for it’s drop down menus in the inspector. i.e with an up and down arrow to the right.

I’m not using EditorGUILayout.Popup because I don’t want to add a delay whenever the inspector is shown which would occur if I created the array of options in OnEnable or OnInspectorGUI. Instead I wish to populate the menu when/if the user clicks the drop down button, at which point in my example I scan the project’s path for scene files.

To use call EdDelayedPopup.Popup and pass it the string or GUIContent you wish to display in the button and a function to call when the button is pressed. When the function is called you can query EdDelayedPopup.ButtonRect to get the rectangle of the button and GenericMenu.DropDown to open a menu there or even use your own custom window.
Continue reading Custom popups matching EditorGUILayout.Popup style

How to disable touches / mouse clicks in uGUI

During screen transitions I disable user input, as the screen we are leaving does not want any more input and the screen we are going to may not quite be ready. So I was hoping that the 4.6 beta 20 release notes of:

UI: Allow users to enable / disable navigation on a global level (including submit / cancel keys). See: EventSystem.current.sendNavigationEvents

meant that it would also disable touch and mouse navigation events but it appears that these still go through.

So I’ve done some research and identified a few methods that could be used:

Continue reading How to disable touches / mouse clicks in uGUI

High Resolution Cropped Facebook Profile Images

When writing our original Facebook integration we searched high and low to try to work out how to get the square profile image at a resolution higher than 50×50 pixels to no avail. The only options we could find were to get the picture, from which your profile picture is taken, at a higher resolution. The problem with this is that it’s not always square and often the user may have setup their profile image to be a cropped area of it.

Well today I was fed up with looking at low resolution images so searched again and managed to find a solution. Using the graph api you can request facebookid/profile?fields=pic_crop

eg http://graph.facebook.com/tactilefusion/profile?fields=pic_crop returns:

{
   "data": [
      {
         "pic_crop": {
            "uri": "http://profile.ak.fbcdn.net/hprofile-ak-prn1/t1/p320x320/10992_567316339955054_1439725697_n.jpg",
            "width": 320,
            "height": 320,
            "left": 0,
            "top": 0,
            "right": 1,
            "bottom": 1
         },
         "id": "447312341955455"
      }
   ]
}

Note that the left, top, right, bottom fields will always be the above they are there for backwards compatibility as it now always returns a cropped image.

So at last we have full res profile images in our new games in production:

Leaderboard