Unity, scalling the width of a dynamically created Gameobject in a a scroll view content box - unity3d

I am trying to add 100 dynamically created buttons to a scroll view in Unity, but I have a problem letting the scroll view automatically adjust the width of the buttons to match the width of my screen.
When I tried to add the buttons manually it worked fine , but when I do this by code I get another results.
The code I am using :
public GameObject button;
public GameObject scrollviewcontents;
void Start()
{
for (int i =0; i<=100;i++) {
GameObject dbutton = Instantiate(button);
dbutton.name = i.ToString();
dbutton.transform.parent = scrollviewcontents.transform;
}
}
and The results I get :
Results
Results with comments
I just want the buttons to look like as they are added manually, any help ???

By default when instantiating an object the object keeps the same world space position, rotation and scale as before. try this instead:
dbutton.transform.SetParent(scrollviewcontents.transform, false);

Related

Unity UiElement created at runtime is not displayed

I created a uielement and gameobject in the runtime and set it to follow the world position of the gameObject.
but the uielement is not displayed.
I've tried a few things and found a way to display them.
public void LateUpdate()
{
var position = gameObject.transform.position;
var newPosition = RuntimePanelUtils.CameraTransformWorldToPanel(gage.panel, position, Camera.main);
gage.transform.position = new Vector2(
newPosition.x - gage.layout.width * 0.5f,
newPosition.y
);
}
Change the LateUpdate function to Update and it will be displayed.
Select Element from the UI toolkit debugger and change the style and it will be displayed.
Change the element style elsewhere than the function that generated the uielement at runtime and it will be displayed.
Following objects already created in the scene works correctly.
Why is this happening? How do I display elements correctly?

Creating multiple buttons using input field in Unity

I just want to ask how can I multiple the buttons by using the input field? Like for example, I typed 100 in the input field and then the buttons will become 100. Please bear in mind that I'm new in Unity. Thank you!
First you need to define what button you want to instantiate, on the UI Canvas or a 3D world button.
public class TestingScript : MonoBehaviour{
// the button to create
public GameObject button;
}
You need to create a prefab or assign an existing button in the world for the script to use as a template when creating them. Next you need to create the input field itself and assign the reference to it through code or in the inspector view, here I am going to have it assigned in the inspector.
// assigned in inspector view
public TMP_InputField inputField;
It should look like this in the component view
Now where you call the function is your choosing, I am doing it through a unity button on which I have the script attached
The method here would look something like this
public void CreateButtons()
{
// here we assume the input is always an integer, otherwise you would create a try catch clause
int amount = int.Parse(inputField.text);
// using world 0 position here, you would need to define where you want them yourself
Vector2 pos = new Vector2(0, 0);
for (int i = 0; i < amount; i++)
{
// the loop will execute the amount of times read from input field
Instantiate(button, pos, Quaternion.identity);
pos.x += 0.5f;
}
}
Note I am using TextMeshPro elements here but the standard unity ones would work too.

Unity: add different scroll speeds in UI Scroll Rect

In Unity, I created a UI Scroll Rect Object. This object has two children, a Button Handler with different Buttons, and a Background.
Using it, both the Buttons and the Background are scrolling at the same speed. I want the Buttons to scroll faster than the Background, thus creating an effect of depth to the scrolling.
I can not find any options in the Objects or the Scroll Rect for this. Any ideas?
This will require a tiny bit of scripting. The best way in my opinion would involve following steps:
a) for each button, add a component that remembers its start position.
b) grab a scrollrect instance in parent
c) using it to grab an instance of ScrollBar
d) scrollbars have onValueChanged(float) callbacks, you can bind to, to know when the scroll position changes (to avoid doing checks in Update)
e) every time a scrollbar has moved (This will work regardless of whether the user used the scrollbar, or used another mean of scrolling, as the scrollrect will move the scrollbar, which will fire the event anyways), you get a callback with current scrollbar position which will be equal to normalized scrollrect position (0.1)
f) use that value to offset your localposition (something value*parallaxVector2), this should give you a nice cheap depth effect
Here's an example implementation
public class ScrolleRectDepthButton : MonoBehaviour
{
RectTransform content; // we'll grab it for size reference
RectTransform myRect;
public float parallaxAmount = 0.05f;
public Vector2 startPosition;
void Start()
{
myRect = GetComponent<RectTransform>();
startPosition = myRect.anchoredPosition;
ScrollRect scrollRect = GetComponentInParent<ScrollRect>();
content = scrollRect.content;
Scrollbar scrollbar = scrollRect.verticalScrollbar;
scrollbar.onValueChanged.AddListener(OnScrollbarMoved);
}
void OnScrollbarMoved(float f)
{
myRect.anchoredPosition = startPosition - (1 - f) * parallaxAmount * content.rect.height * Vector2.up;
}
}

Growing menu with scrollbar

I hate to ask such a generic question but I'm really stuck and super hoping someone can help me along the way. Here is the situation:
I'm making the GUI for a mobile app, portrait mode. I'm using canvas scalers to scale my canvasses with a reference width of 1080. This means I effectively don't know the height of my screen space.
What I want to create is a menu with a variable amount of items. The menu must be anchored to the bottom (with an offset margin) and grow upwards. So far I've been able to manage this using VerticalLayoutGroup and anchoring the rect transform to the bottom.
But my last requirement is that if the content would grow too big, a scrollbar would appear. The definition of the content being too big is: if it would extend the (unknown) screen height ( minus the offset margin of course). I hope the following image illustrates this much clearer:
I have a unity project here: https://ufile.io/v31br
Did you give a try to scrollView? here it is: https://unity3d.com/learn/tutorials/topics/user-interface-ui/scroll-view
You can use your vertical layout inside it and you will probably want to deactivate horizontal scroll and delete the horizontal slider.
Via script you can check its rectTransform height and compare it to your container's size, when reached maxHeight you can start managing your item's sizes
I assume you use the ScrollRect component as it is the right component to use in your case.
You can check the screen height with the Screen.height property.
Once you know the screen height you can compare it with your rect height and toggle the scrollbar with the ScrollRect.vertical property. You may have to change the ScrollRect.verticalScrollbarVisibility to permanent in order to make it work for you.
The answer Dave posted was close, but the problem is that the scrollview doesn't expand. I fixed it eventually by stretching the scrollview and resizing the parent manually as items are added. I set the anchors to the maximum size and adjust the sizeDelta.
public class MenuScript : MonoBehaviour
{
public int MenuItemCount;
public GameObject MenuItemPrefab;
public Transform MenuItemParent;
private RectTransform _rectTransform;
void Start()
{
_rectTransform = GetComponent<RectTransform>();
for (var i = 0; i <= MenuItemCount; i++)
{
GameObject instance = Instantiate(MenuItemPrefab, MenuItemParent, false);
instance.GetComponent<Text>().text = instance.name = "Item " + i;
float size = instance.transform.GetComponent<RectTransform>().sizeDelta.y;
TryExpandBy(size + 10);
}
}
private void TryExpandBy(float size)
{
var deltaY = _rectTransform.sizeDelta.y + size;
if (deltaY > 0) deltaY = 0;
_rectTransform.sizeDelta = new Vector2(_rectTransform.sizeDelta.x, deltaY);
}
}

Unity 5: how to zoom and translate an object from a grid layout to the center of the screen

I'm trying to create a scroll grid view in which every cell object is tapable.
When a cell object is tapped I want to scale and traslate it to the center of the screen and render it above other cells.
I was able to make it tapable and scale it in its position. Now I want to move the cell object to the center of the screen and render it above other cells.
I've tried many solutions but none of them works.
This is my hierarchy:
This is the grid in normal state:
This is the grid when a cell was tapped:
I'm populating the grid from a C# script dynamically.
void Populate()
{
GameObject cardContainerInstance, cardInstance;
foreach (var c in cardsCollection.GetAll())
{
if (c.IsOwned)
{
cardContainerInstance = Instantiate(cardContainer, transform);
cardInstance = cardContainerInstance.transform.Find("Card").gameObject;
var cardManager = cardInstance.GetComponent<CardManager>();
cardManager.card = c;
cardManager.AddListener(this);
}
else
{
Instantiate(cardSlot, transform);
}
}
}
public void OnCardClick(GameObject cardObject, Card card)
{
Debug.Log("OnCardClick " + card.name);
if (openedCard != null) {
if (openedCard.Number == card.Number)
{
CloseCard(openedCardObject);
}
else
{
CloseCard(openedCardObject);
OpenCard(cardObject, card);
}
}
else
{
OpenCard(cardObject, card);
}
}
void OpenCard(GameObject cardObject, Card card)
{
//cardObject.GetComponent<Canvas>().sortingOrder = 1;
var animator = cardObject.GetComponent<Animator>();
animator.SetTrigger("Open");
openedCard = card;
openedCardObject = cardObject;
}
void CloseCard(GameObject cardObject)
{
var animator = cardObject.GetComponent<Animator>();
animator.SetTrigger("Close");
openedCard = null;
openedCardObject = null;
}
I can't figure out how to move the cell to the center and render it above others.
Note that all is animated using an animator attached to the object itself.
Could anyone help me please? Thank you very much!
EDIT: more details
All cell object have the following hierarchy:
where:
CardContainer is an empty object added to use animator on Card child object
Card is the object itself that has a script, a canvas renderer and an animator
StatsImage is the object that slide out when the card is tapped
Image is a calssic UIImage with Image script, Shadow script and canvas renderer
Other component are simple texts.
EDIT: fix in progress
Trying to apply this suggestions I was able to manage the rendering order (as you see on the image below) but it seems that prevent touch events to be detected on the game object.
I've added a GraphicsRaycaster too and now the bottom horizontal scroll view scrolls again but only if I click and drag a card.
Moreover, with the GraphicsRaycaster, the main grid card still are not clickable and it's possible to open the card only if it is behind the bottom panel (if I click on the red spot in the image below the card behind the panel receives che click)
This is the CardContainer at runtime(note that I'm attaching new Canvas and GraphicsRaycaster on the CardContainer, which is the "root" element):
You didn't clarify whether you are using a sprite renderer or some other method but here is an answer for each.
Sprite renderer:
this the simple one. In each sprite renderer, there is a variable called "sortingOrder" in script and "Order in layer" in the inspector. sprite renderer with sorting Orders that are higher is rendered first. All you would need to do is call:
cardObject.GetComponent<SpriteRenderer>().sortingOrder = 1;
when you click the card, and
cardObject.GetComponent<SpriteRenderer>().sortingOrder = 0;
when you unclick it. I hope that makes sense!
Other Method:
this one is a bit harder and I would suggest that you switch to sprite renderers and it will be much easier and more stable down the road, but I can understand if you have already written a lot of scripts and don't want to go back and change them.
Anyway, all you will need to do Is create two layers: cardLower and cardUpper. then create a new camera and call it topCamera. now under the top camera object in the inspector, change the culling mask (it's near the top) and make sure cardUpper is selected. then change the Clear flags (first one) to "Don't Clear" finally change the depth to 0 (if that doesn't work change it to -2). Now objects in the cardUpper will always be rendered above everything else. You can change the layer through script with
cardObject.layer = "cardUpper"
or
cardObject.layer = "cardLower"
I hope that helps!
Ok, so its pretty simple. So you are going to want to add another canvas component to the game object, and check the override sorting to true. Then use
cardObject.GetComponent<Canvas>().sortingOrder = 1;
to place it in the front and
cardObject.GetComponent<Canvas>().sortingOrder = 0;
to put it in the back.
you are also going to need to put a GraphicsRaycaster on to each of the cardObjects
Ignore my other answer about sprite renderers, they are not needed here