Unity c# Image not appearing in UI canvas panel - c#

I have written a method MakeCard() that instantiates a card prefab (having a button) and adds an image to it through the script that uses an array of sprites but the image does not appear in the panel ("Card Pool") under which I'm setting its transform to. I have another method having the same code and it displays the card (with image) in some other panel (works perfectly fine). But the code isn't working for "Card Pool" panel. I am even displaying the index and the name of the card in logs to check if its fine and its fine. pls help!
EDIT: If i change the parent panel of a card from "Hand" to "Card Pool" it displays fine but if i instantiate the card and set its Parent as "Card Pool" it does not display. Hope this info makes any sense!
public void MakeCard(int index)
{
print("Making Card..." + index);
var cardCopy = Instantiate(cardObj, new Vector3(0, 0, 0),
Quaternion.identity);
var newCard = cardCopy.GetComponent<Card>();
newCard.SetFace(myData.shuffleIndex[index]);
print(newCard.GetName());
cardCopy.transform.SetParent(GameObject.Find("Card Pool").transform);
cardCopy.GetComponent<Button>().interactable = false;
}
the other code thats works perfectly fine is:
public void DistributeMyCards()
{
for(int temp = myData.shuffleIndexToStartWith + 12; myData.shuffleIndexToStartWith < temp; myData.shuffleIndexToStartWith++)
{
//localHand.Add(myData.shuffleIndexToStartWith);
Debug.Log("inside for: " + myData.shuffleIndexToStartWith);
var cardCopy = Instantiate(cardObj, new Vector3(0, 0, 0), Quaternion.identity);
var newCard = cardCopy.GetComponent<Card>();
newCard.SetFace(myData.shuffleIndex[myData.shuffleIndexToStartWith]);
cardCopy.transform.SetParent(GameObject.Find("Hand").transform);
var owner = cardCopy.GetComponent<CardOwner>();
owner.photonPlayer = PlayerNetwork.Instance.me;
owner.setCardId(myData.shuffleIndexToStartWith);
if (!PhotonNetwork.isMasterClient)
{
DisableThrowLocal(cardCopy);
}
localHand.Add(cardCopy);
}
}
PS. Its a MP game but I guess that doesn't have anything to do with this problem.

ok so I found the problem. I had to tick the child controls size (height and width) under horizontal layout group component attached to the panel just as the "Hand panel".

Related

How to dynamically create UI elements (journal entries) in Unity3D at runtime?

I'm making a journal app in Unity (C#) and I can't for the life of me figure out how to properly generate the UI (at runtime) of all the journal entries and have it scrollable within a viewport.
So far I've been able to :
generate an empty UI game object "Entry",
parent it to UI game object "Entries",
create a TextMeshPro component in Entry,
concatenate all entries into a string and show the text
But the size of the TextMeshPro component is huge and doesn't fit in the game window, and using scroll rect doesn't allow me to go to both extremes, as can be seen here.
This is the code I wrote to create the UI and show the journal text:
public class ShowEntries : MonoBehaviour
{
TextMeshProUGUI text;
void Start()
{
GameObject entry = new GameObject();
entry.transform.localScale = new Vector3(1, 1, 1);
entry.transform.localPosition = new Vector3(0, 0, -1000);
entry.transform.SetParent(this.transform);
entry.AddComponent<TextMeshProUGUI>();
text = entry.GetComponent<TextMeshProUGUI>();
text.rectTransform.localPosition = new Vector3(0, 0, 0);
text.alignment = TextAlignmentOptions.Center;
text.color = Color.white;
text.fontSize = 0.5f;
}
void Update()
{
DrawEntries();
}
public void DrawEntries()
{
string textFull = "";
foreach (Experience experience in Global.experienceList)
{
textFull += experience.Format();
}
text.text = textFull;
}
}
I feel like there is a more elegant approach to displaying n number of journal entries in the UI canvas but am fairly new to C# so just wanted to post of here to see if I could get some tips. Ideally, it would generate a list of UI buttons (one for each entry) with a preview, that when clicked opens the entire entry, but for now I'm just trying to figure out how to display the text properly.
Thanks a million!
Figured it out! By creating a UI element prefab I was able to instantiate all the journal entries and set the correct values.

controlling a spawned picturebox

I am trying to make a little game coded in c#, the game involves moving enemies.
These enemies are spawned in using the following code, this code is used multiple times to spawn multiple enemies.
private void EventHandler(Action<object, EventArgs> spawnBox)
{
Random randomPlek = new Random();
int xPlek;
xPlek = randomPlek.Next(1000, 1100);
int yPlek;
yPlek = (randomPlek.Next(0, 8)) * 100;
var picture = new PictureBox
{
Name = "pictureBoxLM",
Size = new Size(150, 100),
SizeMode = PictureBoxSizeMode.StretchImage,
BackColor = Color.Transparent,
Location = new Point(xPlek, yPlek),
Image = Leeuwenmier,
};
this.Controls.Add(picture);
}
The problem is that when trying to make them move or collide, Visual Studio can't find the name and gives an error. This is the code i used for collision:
if(PbMier.Bounds.IntersectsWith(pictureBoxLM.Bounds))
{
// some actions
}
How can I call the spawned picturebox in the code without getting an error?
WinForms controls have names, but that doesn't mean you can access them using that name as a C# identifier.
Your PictureBox only has a named reference within EventHandler(), namely picture, but once control leaves that method that reference goes out of scope.
You need to find the controls again, or find another way to reference the generated controls.
So either:
var allPictureBoxes = this.Controls.Find("PictureBoxLM");
foreach (var pictureBox in allPictureBoxes)
{
// ...
}
Or put this on your form:
List<PictureBox> pictureBoxList = new List<PictureBox>();
And then in the EventHandler();
this.Controls.Add(picture);
pictureBoxList.Add(picture);
After which you can use this for your collision detection:
foreach (var pictureBox in pictureBoxList)
{
// ...
}

Creating a draggable map pin on UWP

After following the instructions in the link here How to create draggable pin in windows 10 to give pick location functionality?
I have a half working dragging pin.
Currently the map pin (Grid) starts in the correct place on the map, however, upon dragging the map pin the pin initially pops up to the top left of the screen (0,0) and starts dragging from here.
Upon dropping the pin it appears to have disconnected from the map element itself as you can then scroll the map and the pin stays in place on the screen.
I am using Xamarin.Forms with a custom map renderer.
Following the original example the map would still pan along with the pin dragging, I corrected this by disabling panning upon Grid_ManipuationStarted.
The issue seems to be with the Grid_ManipulationDelta function as this is what removes the Grid from the MapControl children.
I've uploaded a video of the issue onto YouTube. Found here: https://youtu.be/uUkB5Pi5MnA
My code is as follows:
void IMapControls.startDraggable(Location l) {
// Create the XAML
var grid = new Windows.UI.Xaml.Controls.Grid {
Height=50,
Width=32,
Background = new ImageBrush() { ImageSource= new BitmapImage(new Uri("ms-appx:///pin.png",UriKind.RelativeOrAbsolute)),Stretch = Stretch.Uniform },
};
grid.ManipulationMode = ManipulationModes.TranslateX|ManipulationModes.TranslateY;
grid.ManipulationCompleted += Grid_ManipulationCompleted;
grid.ManipulationStarted += Grid_ManipuationStarted;
grid.ManipulationDelta += Grid_ManipulationDelta;
// Set RenderTransform so not null later
CompositeTransform tran = new CompositeTransform();
grid.RenderTransform = tran;
// Add XAML to the map.
nativeMap.Children.Add(grid);
Geopoint snPoint = new Geopoint(new BasicGeoposition() { Latitude = l.lat,Longitude = l.lng });
MapControl.SetLocation(grid,snPoint);
MapControl.SetNormalizedAnchorPoint(grid,new Windows.Foundation.Point(0.5,1.0));
}
private void Grid_ManipuationStarted(Object sender,ManipulationStartedRoutedEventArgs e) {
nativeMap.PanInteractionMode=MapPanInteractionMode.Disabled;
}
private void Grid_ManipulationDelta(object sender,ManipulationDeltaRoutedEventArgs e) {
var grid = sender as Windows.UI.Xaml.Controls.Grid;
CompositeTransform xform = grid.RenderTransform as CompositeTransform;
xform.TranslateX += e.Delta.Translation.X;
xform.TranslateY += e.Delta.Translation.Y;
e.Handled = true;
}
private void Grid_ManipulationCompleted(object sender,ManipulationCompletedRoutedEventArgs e) {
nativeMap.PanInteractionMode=MapPanInteractionMode.Auto;
var grid = sender as Windows.UI.Xaml.Controls.Grid;
Rect point = grid.TransformToVisual(nativeMap).TransformBounds(new Rect(0,0,grid.Width,grid.Height));
Geopoint gPoint;
nativeMap.GetLocationFromOffset(new Windows.Foundation.Point(point.X,point.Y),out gPoint);
Debug.WriteLine(gPoint.Position.Latitude);
Debug.WriteLine(gPoint.Position.Longitude);
}
Solved this by creating a Grid and adding it to the map, then creating an Image and adding this to the Grid. You drag the Image using Delta.Translation as above and upon dropping the pin it moves the Grid using MapControl.SetLocation (Not TranslateX/Y) to where the pin drops, then TranslateX/Y the pin Image to 0,0 (relative to the parent Grid).
This works as the Grid only moves using SetLocation which seems to work fine and doesn't disconnect it from the map like before. The pin moves relative to the Grid and has no issues as before, ie. Moving to 0,0 upon start and disconnecting from the map object.
Cheers!
Can post code if anyone is interested but I think it is pretty self explanatory.

Instantiate prefab in Unity

I'm instantiating a prefab panel in unity and i'm settings it's parent to another panel like this :
GameObject notificationPanel = (GameObject) Resources.Load("NotificationWindow");
Text notificationText = notificationPanel.GetComponentInChildren<Text>();
if (notificationType == NotificationType.Warning)
{
notificationText.color = Color.red;
}
notificationText.text = text;
GameObject newNotificationWindow =
(GameObject) Instantiate(notificationPanel, new Vector3(0, 0, 0), Quaternion.identity);
newNotificationWindow.transform.SetParent(Settings.NotificationHolder.transform);
However when instantiated it's with an insane size, the parent panel has a layout group with a fixed size of the cell's inside of it why isn't this affecting it ? The new panel is around 10 times bigger than my screen. In the hierarchy view the new panel appears as a child correctly under it's parent. Also the 'z' position is around - 3900 why ?
So After reading the Unity Documentation: Instantiating the UI element all you have to do is to call:
newNotificationWindow.transform.SetParent(Settings.NotificationHolder.transform, false);
The "false"represents worldPositionStays parameter and this scales the UI.
Let me know if this works for you.

Slide effect is not smooth

I am trying to move a control to another control's position in a sliding effect. The below code works but it is not smooth as expected. I know repaint has to happen for every one pixel move and that has all things to do with this problem. Is there anything I can do to make it smooth?
void changePage(Control currentPage, Control newPage)
{
int curPageStartX = currentPage.Location.X;
newPage.Location = new Point(currentPage.Size.Width + curPageStartX, currentPage.Location.Y);
while (newPage.Location.X > curPageStartX)
{
currentPage.Location = new Point(currentPage.Location.X - 1, currentPage.Location.Y);
newPage.Location = new Point(newPage.Location.X - 1, newPage.Location.Y);
}
}

Categories