- Home /
Rescaling mesh or GameObject to fit in GUI Rect
Hi guys. I've got some rectangle drawed with mouse
Vector3 topLeft = Vector3.Min(startPosition, endPosition);
Vector3 bottomRight = Vector3.Max(startPosition, endPosition);
//Screen space?
Rect rect = Rect.MinMaxRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
and I'm trying to convert it into some gameobject by instantiating a prefab (basically a quad with attached mesh to it):
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(new Vector3(rect.center.x, rect.center.y, 5));
GameObject go = (GameObject) Instantiate(prefab, worldPoint, Quaternion.identity);
It centers perfectly, but how do I resize it to fit exactly to the size of drawed rectangle?
I can't wrap my head around it. Any ideas?
Answer by VergilUa · Nov 09, 2016 at 07:55 PM
Ok, I've figured it out. Here's a solution if anybody else will stumble upon such problem.
Mesh mesh = go.GetComponent<MeshFilter>().mesh;
Bounds bounds = mesh.bounds;
//Getting xMin and yMin
Vector3 min = new Vector3(rect.xMin, rect.yMin, 0);
Vector3 max = new Vector3(rect.xMax, rect.yMax, 0);
//Converting them to worldspace coordinates
min = Camera.main.ScreenToWorldPoint(min);
max = Camera.main.ScreenToWorldPoint(max);
//Calculating width/height in world space coorinate-size
float width = max.x - min.x;
float height = max.y - min.y;
//Calculating scale factors
float widthScaleFactor = (width / bounds.size.x);
float heightScaleFactor = (height / bounds.size.y);
Vector3 localScale = go.transform.localScale;
//Scaling object
localScale.x *= widthScaleFactor;
localScale.y *= heightScaleFactor;
go.transform.localScale = localScale;
Probably not the prettiest one, but it works.
Answer by ElijahShadbolt · Nov 09, 2016 at 07:32 PM
Assuming the quad mesh's dimensions are 1x1 units, you could set the instantiated object's transform's scale to be the same as the Rect's width and height.
go.transform.localScale = new Vector3(rect.width, rect.height, 1);
It doesn't work that way, since it's a gui rect. I've already submited a working answer, but it's under moderation. T_T
Thank you for your effort
Answer by topitsky · Jan 03 at 04:21 PM
This works pretty well, but its off when the models origin is not a center.
Your answer
Follow this Question
Related Questions
Problem dragging, scaling, moving objects in #scene view with mouse 0 Answers
Questions about UGUI Rect Transform Anchors. How to make UI objects scale, correctly, with screen? 1 Answer
Objects overlapping in perspective rather than real space? 1 Answer
Correct use to scale Text and Rect? 1 Answer
Is it possible to change Rect Transform Scale throw script 1 Answer