How to load images in unity with button click - unity3d

Is it possible to load images in unity with button click.
What I'm trying to do is I will have a list of images in a folder. And with a next and previous button all images will be viewed one after one.

Yes, it's very easy.
Just instantiate a variable from Texture2D and call its LoadImage method. like this:
var T = new Texture2D(1, 1);
T.LoadImage("Address to your image");
Then you can assign the texture T to a RawImage like this:
var RI = GetComponent<RawImage>();
RI.texture = T;

Related

Saving Prefav Data In Unity between scene transition

I am making a game where the data to be displayed in the Main Menu is fetched from the API. I store the data in a class and loop through the data to map the data in the Menu.
foreach(var dt in mainMenuDto.data)
{
GameObject _catogeryPrefabTemp = Instantiate(catogeryPrefab);
Vector3 originalSize = _catogeryPrefabTemp.transform.localPosition;
_tabGroup.objectsToSwap.Add(_catogeryPrefabTemp);
_catogeryPrefabTemp.transform.SetParent(catogeryParent.transform);
_catogeryPrefabTemp.transform.localPosition = originalSize;
_catogeryPrefabTemp.transform.localScale = new Vector3(1, 1, 1);
foreach (var item in dt.games)
{
Texture2D image = await (GetRemoteTexture(item.thumbnail));
tex.Add(image);
await _catogeryPrefabTemp.GetComponent<CatogeryInitialise>().InstantiateGame(gameButtonPrefab, item.slug,image);
}
}
Now , this works fine but when I change the scene and come back to The main Menu, the whole mapping process takes place again. How do I change the main menu to be saved even during scene changes.
Use DontDestroyOnLoad
This method will tell unity to keep your menu between scenes. You will be able to see it under separate DontDestroyOnLoad label in your scene hierarchy.

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

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);

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

Unity 5 change button text created with UnityScript

In my 2D project I create a canvas and a button in code. I would like to set the text of the button in code, but after numerous attempts I can't seem to do it.
My UnityScript code:
#pragma strict
var loginButton : UnityEngine.UI.Button;
function Start () {
var canvas = new GameObject ("canvas", Canvas);
var instance : UnityEngine.UI.Button = Instantiate(loginButton);
instance.GetComponent(UnityEngine.UI.Text).text = "login"; //Error below
instance.transform.position = Vector2(0,0);
instance.transform.SetParent(canvas.transform);
}
This provides an error
"NullReferenceException: Object reference not set to an instance of an object
GameLogicLogin.Start () (at Assets/GameLogicLogin.js:11)"
--------------------------------Edit---------------------------------------
The generated hierarchy looks like this: http://puu.sh/iMYe6/4f4a8f545c.png
On the left at the bottom is the prefab I link to the script.
The following line doesn't cause an error and seems to change the text, but the change doesn't show up in game nor does the original text assigned to the "Text"in the prefab.
instance.GetComponentInChildren(UnityEngine.UI.Text).text = "login";
If you would of built your button in the unity editor you could easily change its text in script like this:
var button = GameObject.Find("buttonObjectName").GetComponent<Button>();
button.GetComponentInChildren<Text>().text = "What ever you like";
I imagine you can easily adjust this to fit your needs without being spoon fed.
You are instantiating a UnityEngine.UI.Button, that doesn't have a component for UnityEngine.UI.Text hence the error.
Is there any reason why you are instantiating that object?
If you are linking in the editor a game object to loginButton, and I think you are, you should do something like this:
var comps = loginButton.gameObject.GetComponentsInChildren(UnityEngine.UI.Text);
comps[0].text = "login";

Using new UI Image component to show a image on web in Unity 4.6

I'm trying to use the new UI objects in Unity 4.6 to create a ranking screen where I download information about the users and show them. Among those informations I have an URL pointing to their picture.
Before the UI tools I was doing it with GUITexture and using the www.LoadImageIntoTexture method, but there doesn't seem to be a similar solution for UI Images. Using a GUITexture with a Rect Transform doesn't seem to work.
Should I just manually download the image and load it into the image or is there a similiar solution as with using WWW class?
The new Image component takes requires a sprite to render.
What should work is download a PNG texture using the WWW class, then creating a sprite and finally assigning it to the component.
Here's some sample code.
Create a new Monobehaviour, paste below code into it (I called my script "LoadImageToButton")
Create a new UIButton
Attach the Monobehaviour created in Step 1 to the Button
In the Button's "OnClick" event, Drag the button created in Step 2 (this same button) into the GameObject field
Select the "LoadImage" function as the function to call for the OnClick event. (In my case it was "LoadImageToButton.LoadImage")
Hit Play, click the button. You should see the button's image change (It looks terrible, but it works)
See the pictures attached for actual results.
//This is the method you call if you use the "OnClick" event from a button click.
//We cannot call the Coroutine function below, because it breaks the rule for
//the event system. i.e. Must be a return type of void.
public void LoadImage () {
//Call the actual loading method
StartCoroutine(RealLoadImage());
}
//This is where the actual code is executed
private IEnumerator RealLoadImage () {
//A URL where the image is stored
string url = "http://www.axsu3d.com/DLs/AxSWP8Plugin/TileLogo.png";
//Call the WWW class constructor
WWW imageURLWWW = new WWW(url);
//Wait for the download
yield return imageURLWWW;
//Simple check to see if there's indeed a texture available
if(imageURLWWW.texture != null) {
//Construct a new Sprite
Sprite sprite = new Sprite();
//Create a new sprite using the Texture2D from the url.
//Note that the 400 parameter is the width and height.
//Adjust accordingly
sprite = Sprite.Create(imageURLWWW.texture, new Rect(0, 0, 400, 400), Vector2.zero);
//Assign the sprite to the Image Component
GetComponent<UnityEngine.UI.Image>().sprite = sprite;
}
yield return null;
}