Hello.
I am working on ToolTip for my inventory system. So far I have most of things, now I am refractoring code and adding additional functionality. Now I wanted to make my ToolTip show on left or right side of mouse based on end of screen (when tooltip is out of canvas simply show it on opposite side). Everyting is fine and I have function to do that BUT! Function that works not on first time! I mean, I have to hover item twice to get proper value of RectTransform (I need it to offset whole panel by RectTransform width) and I don’t know why.
This is my function:
public void ShowToolTip(Vector2 position, int ID)
{
Item gatherItem = itemDatabase.Items.Find(item => item.id == ID);
if(!isDragging)
{
toolTip.GetComponent<CanvasGroup>().alpha = 1f;
GatherItemInfo(gatherItem);
toolTip.transform.SetAsLastSibling();
float rectwidth = toolTip.GetComponent<RectTransform>().rect.width;
Debug.Log(rectwidth);
if(position.x + rectwidth >= Screen.width)
{
Debug.Log("On the Left.");
}
else
{
Debug.Log("On the Right.");
}
}
else
return;
}
GatherItemInfo() method simply fills UI Text inside ToolTip.
And output from Debug.Log:
1st Hover:
2nd Hover:
3rd and others:
Now when I change item:
1st Hover:
2nd Hover:
etc.
Whole situation looks like rectwidth have value BEFORE content size fitter calculate it.
Someone can help me how to solve that? GatherItemInfo() runs before GetComponent so rect should be already calculated, seems it is not.
My ToolTip is simply Panel with Content Size Fitter + Vertical Layout Group and inside it UI Text.
Oh My God. I figured out how to solve that. I just have to:
float textwidth = toolTip.transform.GetChild(0).GetComponent<Text>().preferredWidth;
Instead of:
float rectwidth = toolTip.GetComponent<RectTransform>().rect.width;
Now I have width just after adding text cus rect is based on that.
Unfortunatelly I don’t know why, that doesn’t work for height (same situation as before, proper height is calculated after showing tooltip. To solve that I wrote simple calculator:
GUIStyle height_calculator = new GUIStyle();
GUIContent toolTipContent = new GUIContent(toolTip.transform.GetChild(0).GetComponent<Text>().text);
float textWidth = toolTip.transform.GetChild(0).GetComponent<Text>().preferredWidth;
float textHeight = height_calculator.CalcHeight(toolTipContent, textWidth);
Now I have both width and height.
Hope that will help if someone will have similar problem to me…