#💻┃code-beginner
1 messages · Page 343 of 1
Date.Now()
There's also TimeOnly that is for just the time
Pretty sure that is not supported by Unity, though
also consider DateTime
Using Datetime.Now thanks
Pretty sure you mean DateTime.Now() and TimeSpan
Yep
Confused it with Javascript
I am trying to get rotation value in the x axis of a game object
public Transform target;
var angle = target.localEulerAngles.x;
Debug.Log(angle) ```
When I am changing targets value in inspector to something like 50,60,90 it's working properly
But when I am changing it above 90
For example 92
Output is 88 and it keeps decreasing when I increase more than 90
How can I solve this issue?
Euler angles are not unique.
There are several ways to represesnt the same rotation.
What are you trying to actually do?
joint.spring = spring ```
Trying to change spring value of the object, based on the targets rotation
You can use Vector3.Angle to measure the angle between two directions
Vector3.Angle(transform.forward, Vector3.up);
e.g.
Is there no way to do this with euler angles?
as you have discovered, no: all rotations are stored as quaternions internally
converting back to euler angles can cause weird jumps
Makes sense
I will try this
If you want to measure how far you've rotated from your parent, consider:
Vector3.Angle(transform.forward, transform.parent.forward);
Anyone have an Idea why Health isn't setting itself to maxHealth when I start the game?
oh, actually
something closer to your original design
Quaternion.Angle(transform.localRotation, Quaternion.identity);
This is how far you've rotated from the default rotation
- it is not saved
- maxHealth may be changed by the inspector
(:
chances are maxHealth is set to something else in the inspector
It is set to 10 in the inspector
Have you saved it and tried again?
Can I use this specifically for the x axis?
Then Health will be 10
Yes, I have multiple times. I really don't know why Health isn't 10
good catch, code not saved
I just say that because in your screenshot, that line specifically was not saved
you can always add a Debug to check
I will try that
then show us the console output
Sorry, what is that?
Do you not know what the Unity Console is?
ahh sorry
Can you show me how you're using it? It's a bit tricky...
console is empty, but when I debug it shows up
consider this cube. if I rotate it around its local X axis by spinning the red handle, all three local eulers change
Yeah
so show us the latest code and the console window, we are not mind readers
using UnityEngine;
public class SetHandSpring : MonoBehaviour
{
private HingeJoint joint;
public Transform target;
void Start()
{
joint = gameObject.GetComponent<HingeJoint>();
}
void Update()
{
JointSpring spring = joint.spring;
var angle = 0f;
angle = target.localEulerAngles.x; // Right
spring.targetPosition = angle;
joint.spring = spring;
}
I mean, physically, in the scene!
When I try to change targets rotation.x value more than 90
The eulervalue.x starts decreasing
Hmm
I wrote the full thing above if that gives you a better picture of what I am trying to do
What is target? Is it like a dial that you rotate to make the hinge joint rotate?
It's a rectangular cube
And the local transform is a hand with rigidbody and hingejoint attached
Right now what's happening is
When the target rotates, the hand rotates as well
But as soon as the target rotates more than 90° the local hand rotates in the opposite direction
ah, so you're making a hand follow the thing it's holding
Vector3.SignedAngle can give you an angle ranging from -180 to 180. It sounds relevant here.
Not exactly holding
But an external object
You give it two vectors to compare, as well as a third vector that defines the axis of rotation
(the third vector is what gives you the sign)
otherwise you can't really decide if a rotation is positive or negative
So you DID NOT add a Debug to the Start method like I asked
Not working
Consider making both variables private in order to prevent them from being affected by something else.
Also, yes, that debug should be in start, and log the actual value of Health, not just words
gusy can you help me im a begainer and im making a game i got a video of the issue but i cant sadly send it here
Please do not cross post
Impossible to help you with no information whatsoever
i got the info
but i cant send the video here
it wont allow me
so explain it in words
ok
Hey, im making a small game as a learning project and i want to make a procedurally generated open world tilemap. my idea is making small sections of tilemaps as prefabs and then instanciate them when the camera gets close to the edge of the current map. but i cannot for the life of me figure out how i save a tilemap as a prefab. is it not possible or am i missing something?
I've saved tilemaps as prefabs before, what's your issue with it?
A tilemap is a component. Drag the game object it's on into the project window to create a prefab out of it.
oh are you trying to save the component as a prefab?
prefabs need to be gameobjects iirc
i see my problem, its because of the way my current tilemap is set up. i think i know how to fix it so ill try that first
actually no im not sure. i tried taking the "TileMapBase" and making it a prefab but when i then drag that prefab into the game window, it looks like this. it has saved the collider but not the sprites
are you dragging your tilemap onto a tile grid?
im not entirely sure what that means. i have this in my hierarchy and i dragged the tilemap base into the prefabs folder, and then dragges that prefab into the scene
did it work before you made it a prefab?
and are there any references you're missing?
wait it works. it was because it wasnt on the grid object
lol told you
thanks a lot 🙂
when making an open world like this, is it best to just make a bunch of mountain prefabs and then instantiate them onto a base layer, or should i make both a base and the mountains in the same prefab?
what do you mean by mountain?
my tilemap is made up of a base layer with ground tiles and then i have tiles to make mountains to add some diversity to the maps. when i then make the mountains they need to be on a seperate layer than the ground tiles are. so should i make prefabs of the mountains on the ground or just make prefabs of the mountains and instantiate them on a base/ground layer?
make prefabs of any tile sets and instantiate them on different grids depending on what layers you want
okay thx
np
hey! sorry for the question but can someone explain to me why this isnt working? the script is attached to a button and when i press on the button its not printing "HELLOOOO"
does the button have a collider?
is everything else setup correctly? do you have a collider?
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
i do but its not working
is the script attached to a GameObject in the scene or is it on a canvas?
its attached to the button itself
yeah, but is this a GameObject in the scene or an object in a canvas, like UI?
an object in a canvas
then you're using the wrong method . . .
oh ;-; mb
use pointer events via code or the event trigger component . . .
alright im gonna go research that, thanks man!
OnMouseDown is for actual GameObjects in the scene that you want to click and interact with . . .
OHHH yeah that makes more sense...
I don't know how best to ask this question, but, I have a coroutine that runs near the beginning of my level with two different variables, as soon as the second coroutine is called, it switches the variable and runs both coroutines with the "second value" - is there a way for me to make sure they both run along side, or do I have to split the code into separate coroutines?
why not just wire up the Button OnClick event?
please highlight your code
```cs
@spare mountain I can't find out how to highlight it in chat so I replaced it with a link that should work?
that's fine. here's how in the future when posting inline !code . . .
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ohhhhhh facepalm - thanks!
public IEnumerator HighlightPath(int path)
{
if(path == 1)
{
highlightedPath = PathPoints1;
highlightedPoints = pathPoints1;
}
if(path == 2)
{
highlightedPath = PathPoints2;
highlightedPoints = pathPoints2;
}
if(path == 3)
{
highlightedPath = PathPoints3;
highlightedPoints = pathPoints3;
}
for (int i = 0; i < highlightedPath.transform.childCount; i++)
{
if (i != highlightedPath.transform.childCount - 1)
{
int j = i + 1;
GameObject arrow = Instantiate(arrowObject, highlightedPoints[i].position, Quaternion.identity);
arrow.transform.LookAt(highlightedPoints[j]);
Destroy(arrow, 0.75f);
Debug.Log("I should be highlighting pathpoint > " + highlightedPoints[i] + " & pathpoint >" + highlightedPoints[j]);
}
yield return new WaitForSeconds(1f);
}
}```
it needs to be on the same line as the ```
```cs
test
as such
It didn't like other characters on the same-first-line 🙈
The code runs for # time, then when it's called with "path == 2", the first call is replaced with the new value
what does runs for # time mean
Sorry! The coroutine is called at the very start of the game, then it is eventually called again, but usually the first time the coroutine is called, hasn't finished yet, so instead of carrying on with the first array (PathPoints1), both coroutines are now using the second array (PathPoints2)
does HighlightPath get called again? when path is 2, the method is already running with the current path, no?
the first call wouldn't switch arrays because that happens at the beginning of the coroutine . . .
Game starts
- HighlightPath(1)
GameRuns
- HighlighPath(2)
Game continues, but both of the coroutines are now running with the "HighlightPath(2)" value
If every coroutine should have the same value, just make it a field on the class.
The premise is a tower defense game, I'm showing the path to the player by highlighting the waypoints enemies are walking across. It works okay until I try to show path2 and/or path3 - while HighlightPath(1) is showing and HighlightPath(2) is called, "HighlightPath(1)" (through debug.log) now shows the values according to the new "HighlightPath(2)"
Heya, so I need help with making an infinite runner, I have a parallax background, but the thing is that it's with a fixed camera, and I'm trying to have it so where a group of sprites move and reset their position, I'm not sure how to achieve that.
This is what I have now
And this is the code I'm working with to try and achieve it
[SerializeField] bool scrollLeft;
float singleTextureWidth;
void Start()
{
SetupTexture();
}
void SetupTexture()
{
Sprite sprite = GetComponent<SpriteRenderer>().sprite;
singleTextureWidth = sprite.texture.width / sprite.pixelsPerUnit;
}
void Scroll()
{
float delta = moveSpeed * Time.deltaTime;
transform.position += new Vector3(delta, 0f, 0f);
}
void CheckReset()
{
if ((Mathf.Abs(transform.position.x) - singleTextureWidth) > 0)
{
transform.position = new Vector3(0.0f, transform.position.y, transform.position.z);
}
}
void Update()
{
Scroll();
CheckReset();
}
Granted, I still need to figure out how to implement it as a group instead of relying on the size of a singular sprite
if the highlighted path and points are suppose to be separate, then make them local to the coroutine. it looks like they are class variables which will change when set a new coroutine is executed . . .
any idea what this means
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Unity UI bug, maybe from animator or shader graph. You can clear and ignore it. If it happens again, try resetting the layout
how do i reset the layout
Line 42: spawnPointIndex was too low or too high and doesn't fall in the available range of elements in your numbers list.
Perhaps you meant to do that on the spawnPoints list instead?
If the error was on Line 41 I would agree with you
They access spawnPoints on 41, so they may want to remove them from the available spawn points for the next iteration
Yes they do that on the wrong list presumably
but the index is generated on numbers and the remove is also numbers
I think they changed the script and didn't post the correct version and you are correct it's the Instantiate line throwing the error
its the latest version
big doubt
i checked it is
then the error is not from that version
If there's { 1, 3, 6 } in numbers and 6 is randomly picked out, then the RemoveAt(6) will fail because the list doesn't have an element at index 6
no
int spawnPointIndex = numbers[Random.Range(0, numbers.Count)];
that returns a float, will that still work?
but this
spawnPoints[spawnPointIndex]
could definitely throw an error
does the spawnpoint array need to have 6 or it can have less
no it doesnt
What is this code supposed to do?
Random.Range() I mean
can return float or int depending on the parameters supplied
Assign random spawn points to random enemies?
obstacles but yea basically
8 spawn points, 2 different obstacles but want to add more in future
You should really name your lists so it's explicit on what they are and what they store
yea my bad on that
So, once a spawn point is "consumed" it should not be used anymore to spawn obstacles, correct?
Hence the removal from the list on L42
Made on the wrong list
this
int spawnPointIndex = numbers[Random.Range(0, numbers.Count)];
Instantiate(obstaclePrefab, spawnPoints[spawnPointIndex].transform.position, Quaternion.identity);
is what worries me, an index based on numbers but used on spawnPoints
i still want that spawn point to be used once the timer is reset, but not allow 2 to spawn on the same one in the same iteration
There's 7 spaces and it fills out 6 of them for each "obstacle row" if I read the code correctly
got it
int k = Random.Range(0, numbers.Count);
int spawnPointIndex = numbers[k];
Instantiate(obstaclePrefab, spawnPoints[spawnPointIndex].transform.position, Quaternion.identity);
numbers.RemoveAt(k);
Or just numbers.Remove(spawnPointIndex)
indeed
That eliminates the spawn point that was just chosen
thank you so much steve lol
.Remove(n): removes the first occurrence of n in the list wherever it is
.RemoveAt(n): removes the element at index n whatever it is
oh
I think you're mixing up the two
Just taking the learning opportunity, but is this what you meant? It now does what I expect ```cs
public IEnumerator HighlightPath(int path)
{
if(path == 1)
{
highlightedPath = PathPoints1;
highlightedPoints = pathPoints1;
yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
}
if(path == 2)
{
highlightedPath = PathPoints2;
highlightedPoints = pathPoints2;
yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
}
if(path == 3)
{
highlightedPath = PathPoints3;
highlightedPoints = pathPoints3;
yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
}
}```
If you're finding yourself using numbered variable names (pathPoints1, pathPoints2), you should be using an array instead
This code would be shortened down to:
public IEnumerator HighlightPath(int path)
{
highlightedPath = PathPoints[path];
highlightedPoints = pathPoints[path];
yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
}
pretty sure the two highlighted... variables should be local not class scope
Yep that too, unless there's too much spaghetti already and they're used elsewhere
it's gonna screw up if you have more than one routine running
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
Hi all, so new to newish to unity and im trying to wrap my head round using inheritance.
I get the gist of it but its more so the use of it in other objects.
Did some google searches and im kinda just going in circles following "how to access data from other scripts".
So making a script that has the class and inheriting classes, but now i want to actually use these classes.
So im making entity classes, so for example gonna be using it for animals, Hostile NPC.
public class Entity_Base : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] protected string EntityName;
[SerializeField] protected string Description;
[SerializeField] protected float movementSpeed;
protected enum Entity_Alert_State
{ Idle,Flee,Patrol,Combat}
[SerializeField] protected Entity_Alert_State AlertState;
}
public class Human_Entity : Entity_Base
{
public readonly int HumanNumber;
}```
As a quick example, but now actually *using* it im kinda stumped, if anyone can link me to anything or give a brief guide anything would be appreciated.
private void AnimateMoneyGain(int amount)
{
Vector3 spawnPosition = new Vector3(100, 500, 100);
GameObject gainMessage = Instantiate(moneyGainMessagePrefab, spawnPosition, Quaternion.identity, transform);
TextMeshProUGUI gainText = gainMessage.GetComponentInChildren<TextMeshProUGUI>();
gainText.text = "+$" + amount.ToString();
Animator gainAnimator = gainMessage.GetComponent<Animator>();
gainAnimator.SetTrigger("GainMoney");
Destroy(gainMessage, 2f);
}
private void AnimateMoneyLoss(int amount)
{
Vector3 spawnPosition = new Vector3(0, -100, 0);
GameObject lossMessage = Instantiate(moneyLossMessagePrefab, spawnPosition, Quaternion.identity, transform);
TextMeshProUGUI lossText = lossMessage.GetComponentInChildren<TextMeshProUGUI>();
lossText.text = "-$" + amount.ToString();
Animator lossAnimator = lossMessage.GetComponent<Animator>();
lossAnimator.SetTrigger("LoseMoney");
Destroy(lossMessage, 2f);
}
Any idea on why my texts are not spawning in the right spot?
you have 2 hardcoded spawn positions
Vector3(100, 500, 100);
Vector3(0, -100, 0);
what is wrong with them?
They not in the right postion, I tried editing them but they didnt move the text at all either
looks like you might be trying to use a ui element in world space?
can you attach your human entity script to a gameobject?
that said, if you're just looking to access data from other scripts, inheritance is not a great solution for that
I mean the UI and the animation works, its just the position is off
off like...in your ui canvas instead of in the world?
Did you use the 3D TMPro object?
the way a ui element might be if you tried to use it in the world?
No its a TMP text on a canvis
So Human Entity is in the same script as Entity script.
i was thinking that i can keep all the generalised template in the same script and get references to them or something.
But if its gonna be like Base script, than i create Human script than Dog script i can understand how to use that yeah.
i just was unsure what is the actual method of using inheritance in Unity, since i am more use to Unreal
then you should be using the RectTransform methods
for your monobehavior to work, it must:
- be in its own file
- have a matching class and filename
so if you move your child class into its own file, you'll be able to use it like you are expecting
though you might need to move to PascalCase classes, i donno if unity will like your underscores (but maybe it doesn't matter, not sure)
hm hm well i can do their own scripts
cheers for the help, i was just assuming i could basically make a template script and use what i want from them.
But cheers for the help
hello, question about Cloud Save. I have the sign in page initialized on the Login Scene, and have my loading and saving on the actual application scene. It all works perfectly, but i want to display which user is currently logged in, and display that through a TMP_Text. Is there a way to pull a value from a previous scene? or save that value to the future scene?
your class definition is the template script for objects of that class type, so I think you are misunderstanding something here
By template script i meant like
Entities, items etc etc
maybe it's helpful to understand that 'dragging a component onto a gameobject' is the same as instantiating an instance of that component's class and attaching that to the gameobject
can scriptable objects temporarily save data between scenes?
yep
they exist outside of any concept of the scene
sweett i think i can figure this one out 😄 every time i come to type a question ive been able to figure it out before i send it haha
Parallax Help
rubber duck debuggin 
I have a toy bird i tell my problems to, it does the same effect lol
his name is Scoop, he has icecream and a spin top hat
i wish i had icecream 😦
it feels so good, i finally coded an entire working app with features i never thought i could build myself. It took so many 2am thoughts haha
[SerializeField] private Camera camObject;
[SerializeField] private float sensitivity;
void Update()
{
if (Input.GetKey(KeyCode.A))
{
camObject.transform.Translate(sensitivity * -1, 0, 0);
}
if (Input.GetKey(KeyCode.W))
{
camObject.transform.Translate(0, sensitivity, 0);
}
if (Input.GetKey(KeyCode.D))
{
camObject.transform.Translate(sensitivity, 0, 0);
}
if (Input.GetKey(KeyCode.W))
{
camObject.transform.Translate(0, sensitivity * -1, 0);
}
}
Completely winging it here, I quickly wrote some code for controlling the camera with the AWSD buttons on keyboard
The camera is only moving horizontally, not responding to W or S though. Any idea what's up?
you probably need to convert the input into actual left right forward view and up view
How can I do that at the beggining of my scene some Singleton object will be created?
I have this awake on my GameController ```cs
protected override void Awake()
{
base.Awake();
//GameDataController.GetInstance().LoadGame();
gameDataController = GameDataController.GetInstance();
progressBarController = ProgressBarController.GetInstance();
}
And the objects look to be created as shown on the image, but when I try to acces any of their methods or variables it just throws a NullReferenceException as if this object wasn't working. I don't know if it is something from Unity optimization
I'm not sure I follow
Currently I'm just setting the value of sensitivity manually in the scene view
same, the more i read it the more i get confused XD
You're checking w twice instead of s.
^^^ yee
Oh I'm stupid lol
Thanks
So when I hit W it's moving up and then down the same distance
Or rather I guess it’s not moving it all
Because those are probably considered simultaneous
it goes one way and then the other..
then u see the result at the end of the frame
so u perceive it to be simultaneous
What's the code of your singletons? Are they in the same scene as the gamecontroller, or loaded earlier?
Yeah I imagine nothing actually changes in the actively running game until Update() has finished running, so nothing’s changed on screen, not even at speeds too fast to perceive
So it might as well be simultaneous
mmhmm
nvm, I have the ProgressBarController to find the UI progressBar on each scene using OnSceneLoaded but I forgot ta made it also search for it on the awake in the case that the singleton is created on a scene with that progressBar
Thanks for the help btw, appreciate that
what is the easiest way to check if my camera is getting close to the end of my tilemap? should i do something with the cameras position compared to an empty on the edge of the map, or should i do something like "when the player has moved X in this direction, then add new tilemap on this side"?
private void AnimateMoneyGain(int amount)
{
GameObject gainMessage = Instantiate(moneyGainMessagePrefab, transform);
TextMeshProUGUI gainText = gainMessage.GetComponentInChildren<TextMeshProUGUI>();
RectTransform gainTextRectTransform = gainText.GetComponent<RectTransform>();
gainTextRectTransform.anchoredPosition = new Vector2(-759, 381); // Adjust this position as needed
Animator gainAnimator = gainMessage.GetComponent<Animator>();
gainAnimator.SetTrigger("GainMoney");
Destroy(gainMessage, 2f);
}
private void AnimateMoneyLoss(int amount)
{
GameObject lossMessage = Instantiate(moneyLossMessagePrefab, transform);
TextMeshProUGUI lossText = lossMessage.GetComponentInChildren<TextMeshProUGUI>();
RectTransform lossTextRectTransform = lossText.GetComponent<RectTransform>();
lossTextRectTransform.anchoredPosition = new Vector2(-759, 381); // Adjust this position as needed
Animator lossAnimator = lossMessage.GetComponent<Animator>();
lossAnimator.SetTrigger("LoseMoney");
Destroy(lossMessage, 2f);
}
The text is still not spawning in right position after changing the recttransform
Idk if it is the best option but I have a simple script with two public Vector2, to set min and max cameraPosition. And then I just manually set the values moving the camera and checking where I want my limits. and then clamping the position as show in this code ```cs
// Clamping a los límites establecidos
newPos.x = Mathf.Clamp(newPos.x, minCameraPos.x, maxCameraPos.x);
newPos.y = Mathf.Clamp(newPos.y, minCameraPos.y, maxCameraPos.y);
transform.position = new Vector3(newPos.x, newPos.y, transform.position.z);
What am I doing wrong that my if statements arent making their own clamps?
is what I have but apparently it should do this
you're missing braces. and you need to get your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
should i be worried
yes
how do i fix
i dont think this is exactly what im looking for (might just be me not fully understanding the code). ive made 4 prefabs of tilemaps. when the game is launched, those 4 are on the screen next to each other. when the player (and therby camera) move towards the edge of the already instantiated tilemap, i need a new one to spawn. so hypothetically the player could walk infinitely left and new tiles would keep spawning
would be good to identify where it's coming from - I don't know your project
no, it just means ur font u've chosen are missing a certain character.. and it has substituted some other character for it
alright thanks
liar
there shouldnt be anything wrong since i've legit just added a pixel art pack so
maybe he's never had that error
i frequently use stylized fonts..
and many of them are missing little things.. like ; or { or something similar
if u check out ur atlas / material / font asset stuff you'll see which ones are missing usually
then they wont display correctly in your game if you're trying to use them - that's something to be worried about
but you do you
its usually something u wouldn't use anyway.. if it becomes obvious that one of the characters are different.. u can just go and edit it then..
no need to make a new font asset for a character u wouldnt use anyway
if you're seeing that warning you've tried to use it somewhere
thats not true
but you'll need to investigate where
that error happens as soon as u create the asset
in the textmeshpro asset creator it'll tell u every character thats missing
ohh noo... im missing a □ what ever will I do
well, if its a font ur trying to use u can open the font asset and in the Character drop down u can actually change the ones that are missing
are there any good 2d movement videos i can watch
if you haven't added a font.. then its probably a bug... or an issue w/ the editor
and can probably ignore it
dozens
it hasnt popped up yet
So i went through that thing about getting it rdy for unity and the only difference I see is the attach to unity selection
visual studio = it
Oh, I see. the stuff on the bottom too
heres one of my favorits
alright thanks
does it involve flipping as well bc
https://gmtk.itch.io/platformer-toolkit
theres also this toolkit thing
that helps u learn how a good one works.. as well as having some sample code
whenever i complete the video
my sprite doesnt actually move left
i mean it doesnt flip
actually
i'll just watch the video you sent me
u can use flipX variable..
i see.
or u can scale the graphics -1 on the x axis
most 2d tutorials will cover the flip part..
its the first bug u run into
alright thanks
im having trouble assigning a value to a scriptable object. I think im overthinking it, I just need and input fields text onEndEdit to be the value of the scriptable object string, so I can display it on another TMP_Text on the next scene. I got it displaying the scriptable objects text, but i keep getting an error bc im trying to reference a script not deriving from monobehavior
Show the error
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you cannot use GetComponent to reference something that isn't a component
Ok yeah. Can't do getcomponent of course
public void SetInputFields()
{
pass = password.text;
user = username.text;
userInfo.Username = user;
}
Just drag it in
okay lemme try
Hmm and even after the updates when I do an if statement it isnt popping up the brackets
anyone?
Code completion is context-aware, meaning it won't show you nor do the same thing depending on where the cursor is in the code. If statements must be inside methods so make sure that's the case on your side.
shoot, i forgot what its called, but the concept is in this 2d youtube vid "How to make your first Game in unity" with the flappy bird thing
Yeah they must be placed in the brackets. The issue Im having is when following a tutorial, he hits tab to bring the text forward. typed if and when he does wiggly brackets pop up underneath with its own set of dotted lines to connect
mine isnt doing that
even though its set to
Do you see the Unity types like Rigidbody, Transform in the completion list as you type, and are errors underlined red live as you type?
errors are underlined yet
let me test the other part
yes to the second part
as you can see from that screen shot, if only goes two brackets deep
this shows that should go 3
when I do an if
They invoked a snippet, by completing if and hitting Tab a second time
You can still type the brackets manually if you want, but snippets are faster to use. In the completion list their icon is a white square with a dotted bottom line
ive been skimming through it but he just makes an empty to spawn pipes at a specific interval. i need to spawn a preset when the player gets too close to the edge
Second to last icon at the bottom of the completion list in this screenshot
that would be like a raycast thing instead, are you in 3d space?
no its a 2d, top down game
i can send some screenshots if that makes understanding easier?
You can have min/max position that tiles exist and min/max position of visible area then compare between them
how would i get those values?
do i just create an empty and then when i spawn a new one, disable the old empty?
That’s up to you, for the existing tiles you can calc based on your tile size, and for visible area you can calculate with your camera size and aspect ratio
what way do you think would be the easiest to do?
I mean for prototyping you can just implement spawning then think about optimization later
You need both currently spawned tile bounds and currently visible bounds
should the script be in my singelton, the grid, or on each prefab?
Should be on whatever object that is responsible to manage your map
If there is none yet then make one
okay thx
ill see if i can make the thing with emptys work and come back here if i cant
How do I find a GameObject by a script attached to it?
Search with t:MyComponent
You need full component name
Or use QuickSearch.. though it was heavy when I last used it
im watching a tut on how to make a game multiplayer and when deciding to join as a host or client the oyutuber makes 2 seperate buttons for them, and also, he makes those buttons in the same scene that the client would join on.
What if i want it to check if there is a server, and if not, join as a host, otherwise, join as a client, and to do so in a different scene, like from main menu scene, you click play, looks for server, lets say it found one, then it joins you as a client i nthe game scene
my eyes
hahah
how do i instantiate an object as a child of a parent object?
By reading the documentation
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
ahh mb
usually you can find it by letting the IDE guess the next selection, or the list it gives, and the descriptions. It helps you learn about other uses of it too
If your lazy^^ hehe
how do I stop visual from replacing Other with coother
what is coother
and why does it auto correct everytime?
Any idea how to fix when Unity doesn't show the regenerate project files option?
make sure you have the visual studio editor pacakge installed and up to date
And that your Unity version is recent enough, IIRC the older ones don't have that option
Don’t think this is Unity related, there should be some option in VS setting
any1? 😢
Ok, thanks
when i instantiate my tilemap prefab, what part of that is instantiated at the given position? is it the center or like the bottom left? hope that made sense
set your tool handle to Pivot and open the prefab and select the root object. where the tool handle is at is the 0,0 position
if anyone here remembers me from asking for help yesterday i made a video on what my problem was
will provide reply context if needed
public class SteeringWheelMapper : MonoBehaviour
{
public TMP_Text debugText;
public Transform steeringWheelTransform;
public float maximumDegrees = 270;
public float MapRotationToValue()
{
float rotationZ = steeringWheelTransform.localEulerAngles.z;
float mappedValue = rotationZ / maximumDegrees;
return mappedValue;
}
void Update()
{
float mappedValue = MapRotationToValue();
debugText.text = mappedValue.ToString("F2");
}
}
I am trying to remap the localEulerAngles.z into input from (-1;1) based on the value. So -270 is -1 and +270 is 1. It is working fine when turning the steering wheel right (correctly maps the values) but when turning the steering wheel left, the values are positive, not negative, why is that
is it because the localEulerAngles are from (0;360)?
i have set it to pivot and opened the prefab. how do i see the tool handle?
click the root object. and look at the scene view
ahh so in this case, if i spawn at 10, 10, then this is the point that would be at that location?
yes
okay. can i change that somehow?
move your tilemap
or place the tiles again so that it is in the center (or where ever you prefer it to be relative to the tiles)
okay thx
I have a problem and that is when I added in the projectile attack, these error tags keep on appearing even though everything works
Attack script, line 14. You pass null or an empty string to CompareTag()
This is not allowed
On one of your objects, attackTarget or attackBigTarget (or both) has no value in the Inspector
Find all objects with this script on, and correct the mistakes
ok
Search for: t: Attack in the Hierarchy's search bar and go through all results.
Also check prefabs
https://gdl.space/onekuvequt.cs but what about with the tag errors that keep on appearing whenever i shot a projectile like the pickups and ground2?
Same issue - look at the stack trace, it contains the file and line of code that triggered the error:
Here, ProjectileAttack, line 28
ahh, the attackBigTarget
It can also be attackTarget, note that you have two calls to CompareTag() on the same line
huh? Enemy and BigEnemy can be on attackTarget?
No I mean you have two variables, attackTarget and attackBigTarget, these may have no value in the Inspector
It's not about which script is attached to the object (the error tells you which scripts the errors originate anyway)
There are of course multiple scripts with these variables (you showed two) so go through each error, each stack trace and fix them all
well the reason why i call ig BigEnemy because i thought of bigger enemies with 3 health, lost most platform games
I don't know why you're talking about some "BigEnemy"
I did this instead
Ignoring the problem entirely I see
As long as it works, I guess
You just had to go to the Inspector and fill "BigEnemy" there in the field, but seems like it's too complicated to do
every time i move an object using Input.mouseposition; the Z is -79.9999 (Unity2D)
Why is that?
well.... there is one i didn't filled which is Groundpound,
you're actually putting it at z 0 for that line. however the position you see in the inspector is relative to the parent
I can't give you the answer why is -80 but you can change the x and y from your transform taking the mouse position and maintain the z ```cs
Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z);
so i tried this, but it still goes to -80
none of the parents have -80 either
If that's a UI object, you should change the RectTransform's anchoredPosition for best accuracy
Show the camera's transform component, the target's transform component and the hierarchy.
i probably have some other piece of code interfering tbh
again, the position you see in the inspector is not the world space position. it is the position relative to its parent object. this object is going to 0 on the Z axis, but that's on the global Z axis
otherwise this makes no sense
oh, so how do i put it at z 0 (so it shows 0 in the inspector?)
when i tried that, i got this:
Is this a UI object?
Why are you converting that to world space
because if i don't, it goes offscreen
i use pixel perfect, idk if that's why, but my screen resolution is MUCH smaller in game than on my pc
ScreenToWorldPoint for perspective cameras needs z to be non-0, such as the camera's nearClip plane value on said camera.
i guess i kinda managed to bootstrap fix it by setting z to 8 rather then 0 lol
any1? 😢
this isnt for #💻┃code-beginner , you can use #archived-networking
also that tutorial or others should cover that i think
https://gdl.space/borilemabe.cs shooting the projectile is working, but however when i turn to the right side, the projectiles are shooting to the wrong way, how can i fix that?
Maybe I am dumb, but is there a way to set the animation speed of an animation clip without an animation controller?
How are you playing it
I just want to play a one shoot on a trigger but it needs to have a variable speed
use Input.GetAxisRaw
From code, like I can just do animation.Play("animationName")
And what is animation
You should not be using the legacy animation component. Use an Animator Controller
I don't need an animator controller to play just a single clip, is unnecessary
anim["name"].speed = 2 for double speed?
I am making a game where there are a wide variety of Characters. These Characters all have the same stats, but not values for them. For example they all have jumpForce, moveSpeed, attackCooldown, and attackDamage. I am wondering how I can make a PlayerStatManager script that I could change overall stats of the Character there.
create that script and make each character reference that script and its stats
What would that manager do specifically?
It will simply be a hub for me[Dev] to change the values when needed, or when the Player upgrades their stats.
Seems like you don't need that, just have prefabs of each character with copies of the script with the values setted previously
So is this manager per-character or per-game?
per character.
I see, just fyi term Manager usually used for singletons so it might cause some confusion when asking
That was the first idea, but I don't enjoy how I have to reference every single script like PlayerMovement, PlayerJump, PlayerCollision, etc just to change values in them. Instead I could change them in a PlayerStatsManager that will change them for me.
Anyhow you would expose this CharacterStat component per character and have it manage the attached character’s stat, so it would have variables or dict for stat type
you dont need to?
Oh, I usually just have all of them in the same script, which I should probably not do to be honest
It isn't a requirement. It will just help me easily get reference to the stats and change them.
Just make a script that holds parameters for all the stats, and make it that on awake, it sets parameters of all other scripts, you just need a reference for them
This is good way to go
I don't think that's a thing...
Okay, I found out how I will do it. Thanks for the help!
Yeah, small scripts with single intention are good. You could have some automation with script if needed, like dependency injection
Single responsibility
I still agree with this daleo_dorito.
Regardless, the animation component is obsolete and should not be used at all
Oh, I can set a clip on the array, but not the whole thing
Okey, sure
Oh, I wasn't going to use a singleton. I was not sure how to make it work with the many characters.
I was going to have each Character have its own PlayerStatManager script on themselves.
Do you think a singleton would be more efficient?
In the image each GameObject with a red line on it is a Character.
I think it is completely fine for stand alone clips, animation controller is unnecessarily complex for those cases
Strongly disagree with both claims
Why though?
What issue does it has?
I think per-character is good way, just that the naming gives the impression of singleton
How is the controller complex at all? It is not
It has been obsoleted
Hi, could someone tell me how to do this in a more intelligent way pls?
look, it's kind of functional, but it doesn't seem to be the smartest way to do it, especially when I still have to check if the gameobject is being occupied or not
Alright, this works then. Thank you! 
Issue is that it is legacy and you won’t get support in future. If you encounter an issue the response is most likely be "use animator instead" 😌
But I agree with your point that Mecanim is tedious for small simple animations
Is more complex precisely cause it is way more flexible, when I don't need that I just don't use it, and even though it is obsolete it has worked every single time for me for simple stuff
legacy doesn't mean it will loose support, it remains there specifically for situations that require a simple solution.
Yeah not sure if it is actually deprecated or planned to be deprecated, but Unity is hiding it from docs and menus
brooo i need some jesus organizing this code XD oh my ogd
As they have announced they are working on a new ECS-based animation system, I imagine both will be deprecated
the docs clearly mention it as the "simple solution", there is no warning or mention of it being removed or obsoleted
hello , this is sliders that exist already in unity , i want to use them as a gameobject , i want to instantiate them , destroy them , and position them with a transform just like normal gameobjects
can i do that ?
Could someone help me with this? please
you also need to actually call the method somewhere
Never call the function, and also just the word "print" randomly in there
sure, or move it outside and actually call it and make it run
Well, that's not how you do that either
You can still see they try to discourage use of it, starting from refereing it legacy rather than simple or something
you just said whats wrong
If you're not getting error highlighting and autocomplete, you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
and how would you do that
might just be your interpretation of what "legacy" means
ok but... what code
exactly which part do you feel isn't right? what behaviour are you aiming for?
how would you print something
ok, so you dont just write print and expect it to work
you tell it what to print
the same concept applies here in Unity
I don't think this is a sustainable way, since you would have to create a game object for each space on the grid, which doesn't seem right to me, but maybe I'm wrong.
And how, if I continue with this model, could I check if, for example, a space is already occupied, and then I wouldn't be able to place another card in the same place?
should i also snet the projectile script?
so you're happy with having a grid for each possible card position?
having a GameObject just for an anchor point to represent each slot isn't too expensive, though looping through each is quite unnecessary. You should probably define a 2d array that contains every Node/anchor, and write a function that directly maps a cursor position (x, y) to the closest node directly. If it's not clear how to proceed I can expand a bit
Sure, or yours 😄
To be honest, I wish it wasn't like this (a grid for each possible position of the cards), but I'm in a gamejam, so I think the best choice is to do it in this easier, but slightly less practical way.
but now that you've said it's not that expensive, I feel a bit lighter XD
do you think I should change the list to an array? this is the current code I'm using:
I mean it works, and looping through 30 or so positions is really not a lot, especially if you're only doing it in response to user input.
Usually for grids though you'd want to have some kind of array, GameObject[,] and to write a few functions that transform coordinates from where you click/world space/screen space x,y to which grid cell it is i,j and vice-versa
If you didn't want a grid at all, just let the cards handle their own position - they are already their own objects. It's not clear what behaviour you'd like for the game and why that wouldn't work though. Each card can have its own event handling for clicks, based on a raycast from your cursor position (if you're using EventSystem most of the awkward stuff is done for you)
Yo boys I need some help
I'll try with the array, thanks for the tip! I've spent all day reading so much about this that I think what I need most is sleep XD
Okay so I’m trying to make the player transfer to another scene (inside house) but I can’t figure out how to make the inputs for it. I made a box collider and made it ignore the player so that I could make that a trigger field all I need is the code for something like that
use the method that listenes to triggers
then switch scene
I’m sorry but please simplify
Actually I’ll go to google
Thank you sir
bro this makes no sense,
projectile is literaly defined
HOW IS IT NOT DEFINED
im trying to destroy the object is it has the tag Projectile once it hits player
as you see in that code
Any whitespace on tag manager
what that
it detects the collision with player using tags
Are you sure it's Projectile and not something like Projectile
but im trying to remove the object projectile once it hits it
okay ill check
Agree on this one.
I think last time I used tags was 2019 lol
I have yet to use one.
GetAxis
And an animator
These parameters are meant to no be used, since they are jut to show for debug purposes. Is there a way to tell the script that so it doesn't show as a yellow error?
Oh wait nevermind they're particles, different .Play
GetAxis uses a float, so you can check if its not 0
also gives you Horizontal (AD/arrows) or Vertical (WS/arrows)
Comment them out
I am using vscode, is there a way to rename script that will auto rename the class name as well?
No, like, I want them to show in the inspector as a parameter but I don't want them to do anything at all
yeah if you use GetAxis it will be literally 2 lines
what the heck is ~=
lol
you mean != ?
ah ok . Yes ! means NOT
afaik ~ invertor for bitwise * in c#
edit
Bitwise complement operator . Thats a mouthful
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators#bitwise-complement-operator-
like i tried to have the projectile shot to the left-way if the player is facing to the left but it is not working
Share the relevant code.
are you sure script is running ?
was it working before changing
are you sure you want Play instead of Emit
try it
its probably because it being constantly called
before you had KeyDown
which is single frame event
now you're doing basically GetKey
which is held-down-like behavior
what is the error
you can probably do
https://docs.unity3d.com/ScriptReference/ParticleSystem-isPlaying.html
yes emit wants the amounts of particles you want to emit at once
start with 1?
As many as you specify in the particle emitter settings.
Play just plays whatever you have set there in main component
i got a situation. I have x and z axis movement and would like to use the magnitude of the button press to drive a blend tree but if i move diagonal i get a value of two rather than the higher value between the button press.
why do you want higher value ?
You can try the other way with .Play()
just put if(audioSource.isPlaying) return; before it
So you want to normalize it 🤔
I would use this
https://docs.unity3d.com/ScriptReference/Vector2.ClampMagnitude.html
relevant code?
Yes. Relevant code. You only shared part of the relevant code.
https://gdl.space/enuqugimix.cs i did sent the projectile code
YOU WERE RIGHT
also what is the spawnPoint.rotation set at when shooting that way, I would not flip the sprite only, i would also rotate the player
tnx
Ok, then I didn't see it around the linked messages. Might want to share it in the same message next time. I'll have a look.
how do i get text to light up? If i do this (which works on images) it shows as full black (even with lighting)
wdym "light up"
also use TextMeshPro
a sprite Material on a text is probably not very good idea btw. Everything should be changed in the appropriate shader, again TMP
Add a debug log in the start and set direction methods and see what prints first.
Nevermind what I said. You don't seem to be using the direction at all:
public void SetDirection(int dir)
{
direction = dir;
}
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = transform.right * speed;
Destroy(gameObject, lifetime);
}
why is direction an int lol
They set it to 1, -1. I guess the intention is multiply the velocity direction.
oh that makes sense ig
personally would rather Flip the whole player 180 on the Y
keeps everything properly as transform.right usually
so, i use URP with 2d unity (unity 2021.3.38f1) and I couldn't find a "lit" text material to apply. How can I do that? (can you point me to a google search or smth? Also, what is TMP?)
forget about the Lit text material, use TextMeshPro . Its inside unity , the new Text component
it might ask you to import TMP essentials when you first add it
TMP is TextMeshPro
yeah
text mesh pro doesn't let me use the font i downloaded, how can I use the other font? Also, what settings will make TMP work with lighting?
TextMeshPro comes with a font creator , you can easily convert it to a TMP font
wdym work with Lighting ?
I want my text to not be lit and to require light to read
how is the "mesh" version called in the components?
how do you guys practice with unity
like the unity interface and knowing what to find and what to use
just TextMeshPro Text
well the player do have a flipmodel code
I just click stuff
jk
use the Manual or Docs
where
how would i use TMP mesh version to use the light? or masks?
here https://gdl.space/ayaluzozav.cs. but since it's stoo long and it can be hard for you to find the flipmodel, here
private void FlipModel()
{
if( (Input.GetAxisRaw(_horiz) > 0 && _isFlipped)
|| (Input.GetAxisRaw(_horiz) < 0 && !_isFlipped)
)
{
_isFlipped = !_isFlipped;
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
}
}
ok..
anyway, just pass the proper directin when you shoot the bullet
Isn't this supposed to return the opposite rotation to the one of the object with the script?
Cause it is not doing that
if its a mesh you can cover it with anything, like a quad
Define opposite rotation
like to try that so flipmodel also flips the projectile attack script?
Same vector from the origin, opposite direction
what ? no.. You literally wrote this int as direction, but you're not using it
Okay, but quaternion is not a vector. You need to start from there..
Inverse of identity quaternion is identity quaternion
Then what the heck is the Inverse method mean to do if it can't be used with Quaternions?
Is literally a quaternion method
why not try printing the euler angles of before and after
make sure they are what you think they are
Inverse means
a * b * inverse(b) == a
Nothing to do with 'direction'
I mean I know the input and the output cause I am checking the rotation of both objects, but they don't even make sense to me
Rotation is not defined with single vector
If you want vector math, rotate forward vector with your quaterion and modify it to get new quaternion
Rotation of the projectile that is instantiating the particle // Rotation of the instantiated particle using Inverse
Is making the negative in eulers or what?
I don’t think messing with euler will give you preferable result
That's clearly not the opposite of the projectile rotation...
IEnumerator SpawnProjectileAfterDelay()
{
yield return new WaitForSeconds(shootingDelay);
int direction = spriteRenderer.flipX ? -1 : 1;
GameObject projectile = Instantiate(projectilePrefab, projectileSpawnPoint.position, projectileSpawnPoint.rotation);
ProjectileAttack projectileController = projectile.GetComponent<ProjectileAttack>();
if (projectileController != null)
{
projectileController.SetDirection(direction);
}
}
``
forward * rot * -1 this is probably the direction vector you are looking for
You have to show the full context of the code
this isnt relevant to what i said earlier
Then create new Quaterion with it, could be LookAt with up vector
do you think it have something to do in the projectile script that any reason why it's not switching direction?
Your set Direction doesn't do anything with the value passed it
huh?
think for a moment about your bullet script
How do you think direction is doing anything here
You know what just do
transform.forward = -transform.forward and see if that is what you want
different person, with different issue lol
they probably thought you sent the earlier one to them
@frigid sequoia
Maybe, I am checking it
hmmm... rb.velocity = transform.right * speed * direction;?
And the bullet is basically just spawning and moving forward each frame, so that's what the rotation does
Setting transform forward will change rotation
tried it but projectile still shooting to the wrong direction even though I'm facing left
first things first, Pause the game when you shoot a projectile facing left side
if you have trouble clicking pause on time, you can use Debug.Break after Instantiate to automatically pause
then show both the shootPoint gizmos and bullet selected gizmos
manage to pause it, and skip on the arrow one time to get to when the projectile appear
ok thats good is paused, but you have not selected with the move tool neither of the objects I asked lol
the center point where projectile shots from to flips around. and here is the projectile object
you're still not in the Move tool, you're in rect tool
also put it in Pivot mode not Center mode
never do Center mode to accurately config your character parts
yeah I mostly just use Center mode when Extruding meshes in Probuilder
i don't have pivot mode though, i only have center and local
Center is the pivot mode.
this thing
you always want it on Pivot
anyway so your bullet is going Right still ?
there, pivot mode
yeah
ok ima make a thread since I know this probably gonna be a whole process
yeah
Man, I don't know what is wrong. I changed it to Quaternion.identity just for testing and shoot at different angles agaisnt some walls. And added a Debug.Log script to the particle to tell its rotation. Isn't Quaternion.Identity supposed to be always the same?
identity should be same so something else is changing your rotation
Oh, ok, I am fucking dumb, there was something wrong with some old logic for bounces
This does work now, but I kinda annoyed I cannot set that directly in the instantiate rotation
I mean you can make rotation from it
Quaternion.LookRotation
Oh, I though I needed a position in the world for that, I guess transform.forward is one too
LookRotation as static function takes direction while LookAt in Transform takes position
legnnd
Is there a way to set a speed of an animation in code? I am trying to make an animation length slower or faster depending on the attackCooldown. How can I achieve this?
fast forward an animation? or only play 50-60% of it?
There is a speed paramter in the animation controller
No, I am talking about adjusting the speed of an animation.
Does that control the speed of which the animation lasts?
It is a speed multiplier
https://docs.unity3d.com/ScriptReference/Animator-speed.html
you can also reference the animation clip inside the animator and change the speed param
I'll try these suggestions thank ya.
public event EventHandler<OnDeliverySuccessEventArgs> OnDeliverySuccess;
public class OnDeliverySuccessEventArgs : EventArgs
{
public float amount;
}
OnDeliverySuccess?.Invoke(this, new OnDeliverySuccessEventArgs
{
amount = recipeSO.price
});
different script
private void DeliveryManager_OnDeliverySuccess(object sender, EventArgs e)
{
moneyHandler.SetMoney(this,e.amount << error shows up here "Event args doesnt contain a defination for amount );
}
hi guys
my problem is that
my event subscrber function isnt getting the event args
for some reason
DeliveryManager_OnDeliverySuccess uses EventArgs as the type instead of OnDeliverySuccessEventArgs . . .
EventArgs does not have a definition for amount, but OnDeliverySuccessEventArgs does . . .
Change the word EventArgs to OnDeliverySuccessEventArgs
it doesnt work man
you didn't change the type from the method declaration . . .
And what does the error say?
where does the class exist?
in another script
i have done this before
with other events
it shows the error in this one only
then you need to correctly access the type . . .
Ok, super basic error. Are you using a namespace?
Oh, is it declared INSIDE a class?
yea
if it's inside a script, then it's nested . . .
that's similar enough, i'd say . . .
Then access it from that type
Yeah true haha
access it correctly from the parent class or place it in it's own file . . .
im sorry im a bit confused , how do i like do this
how do i acces it correctly
if it's inside of a class, then you need to access the class first before you can access the child class, no?
the same way you're trying to access e.amount. amount is a field of e (which is OnDeliverySuccessEventArgs) . . .
is it a bad idea to use binary formatter for a single player game
OnDeliverySuccessEventArgs is a child class nested inside of another class. you need to access the other class first (using dot notation), in order to get access to the child class . . .
ah ok
understood
thanks
thnak you very much
got it
yes, why would you want to?
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
trying to get rid of my dont destroy method of persisting items in game cause that seems to be whats causing the problem
and after a day of debugging and potential fixes im still at square 1
so im just going to make a room manager
🤷♂️ might be better to say what your actual problem is instead of asking about solutions for something we are unaware of.
There is a major difference between DDOL and saving data to file, which i assume was the goal with asking about binary formatter.
well i did post a video showing the problem
and after todays debuggin its either the onItempickup in my inventory controller or the slots script itself
true, but no one here would know that at the moment. best to just link to it so anyone available now can catch up . . .
well you posted a video and said "if anyone remembers the problem". theres no way anyones gonna help you in such case...
when you post, there should be full context
yeah thats my bad ive been stressed trying to figure this out
not sure about other people, but i especially dont really like watching videos to help people. half the time the video is useless. Like "hey guys my character doesnt move". then its a 3 minute video of them scrolling quickly through code, and then showing their character not moving.
ok i get that
it is a lot simpler if you can isolate the specific issue and post code related to it. If you arent able to isolate it at all, (which some problems are hard to isolate), then you likely just need to add more debugs. see what values are, and if they arent what you think it is then that is now relevant code
but i literally ust recorded what the problem was i literally got to the point
I just watched it and have no idea what the issue is
the problem within the video is the items only show up in the inventory is you grab them first before leaving
if you leave then come back the item will not show up and in Debug.Logs
does not even register that your item has been slotted
tho the pickup script does still work
public void Restart()
{
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
Destroy(gridMemory[i][j]);
}
}
gridMemory.Clear();
tilesLeft = width * height - mines;
GenerateGrid();
}
So I wrote this function for resetting a grid I generated, gridMemory is a List<List<Instance of Prefab object>> object where the exterior list is size width and the interior is size height
Initially the nested for loop wasn't even there because I thought the Clear would take care of it, but after that didn't work I tried deleting every object individually and that also did nothing
So I'm confused
Is it actually type Prefab?
Oh, edited. Nm
did you debug if this code was actually running?
It is running
What happens is it generates a second grid but doesn't delete the first
So I've got overlapping tiles that don't work
At least as far as I can tell
It's Minesweeper
If you really need help, I suggest starting a thread that provides all the relevant information(explanation, video, code, debug results). Also, maybe record a shorter video(10-20sec) that shows the exact moment of the issue.
Are they just being cleared from gridMemory but not from the scene somehow still?
What type gridMemory exactly? Share the whole script.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Uh sure
Tile.cs
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
public class Tile : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] SpriteRenderer Renderer;
[SerializeField] public bool hidden = true;
[SerializeField] public int val = 0, x, y;
[SerializeField] Sprite revealed;
[SerializeField] public GridManager grid;
[SerializeField] private bool isClicked = false;
void Start()
{
revealed = grid.getSprite(val);
}
// Update is called once per frame
void Update()
{
if (!hidden)
{
Renderer.sprite = revealed;
if (val == 9 && !grid.lost)
{
grid.Lose();
}
}
}
public void OnMouseDown()
{
if (!isClicked)
{
isClicked = true;
}
}
public void OnMouseExit()
{
isClicked = false;
}
public void OnMouseUp()
{
if (isClicked)
{
hidden = false;
if (val == 0)
{
grid.clearSurrounding(x, y);
}
isClicked = false;
}
}
public void CheckSurrounding()
{
hidden = false;
if (val == 0)
{
grid.clearSurrounding(x, y);
}
}
}
CameraScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
[SerializeField] private Camera camObject;
[SerializeField] private float sensitivity;
[SerializeField] private GridManager grid;
[SerializeField] private ButtonScript button;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.A) && camObject.transform.position.x > 0)
{
camObject.transform.Translate(sensitivity * -1, 0, 0);
}
if (Input.GetKey(KeyCode.W) && camObject.transform.position.y < grid.GetHeight())
{
camObject.transform.Translate(0, sensitivity, 0);
}
if (Input.GetKey(KeyCode.D) && camObject.transform.position.x < grid.GetWidth())
{
camObject.transform.Translate(sensitivity, 0, 0);
}
if (Input.GetKey(KeyCode.S) && camObject.transform.position.y > 0)
{
camObject.transform.Translate(0, sensitivity * -1, 0);
}
}
}
Yeah, so it's a component. Destroying it would just destroy the component. The gameObject itself would be intact.
What you want to destroy is component.gameObject
Oh ok
That's what I get for using var when instantiating
I didn't know exactly what I was working with
Thanks
It's not due to var, but the prefab type Tile TilePrefab
But yeah, if you didn't use var it might've given you a clue
Yeah I created the initial GenerateGrid() with a youtube tutorial and then customized it to be for the game I was working with, but I didn't change that part
https://hastebin.com/share/vocexepuha.csharp
InventoryController
https://hastebin.com/share/irepaludoy.csharp
ItemSlot script
Short explanation: if it grab the items before leaving the room they show up in my inventory ui and debug log tells me the item data has been filled in but if i leave before grabbing them and come back the log does not fire off one but
note: the items are children to a empty game obj with a dontdestroy script to keep things persistent
tried to record a shorter video the best i could
how do i make particles fly a different direction
posted there 5 hours ago
then don't crosspost. and maybe provide literally any details about what you are actually trying to achieve and maybe someone will take the time to help you
Ill be real. I saw your post but I literally needed any detail about what you were actually trying to achieve
ok
basic ethics
if someone is available to help me on Object Pooling, asking very kindly
did you even bother reading the page that was linked
no, ask what issue or problem you are having. post the code in question, and any errors you have . . .
no i cant cuz i gotta solve my issue first
okay got it
well you won't solve it until you actually ask your question
the link tells you how to properly ask a question . . .
i tried this but my problem was ignored, so i thought asking before sounds beter uk
you have now spent 3 minutes just beating around the bush instead of asking your question. it is entirely possible your entire issue could have been solved by now
people are less inclined to help without actual information. asking about a general topic steers them away because they don't know the scope, skill required, or time complexity of the problem . . .
i read that and its very generalising
u are correct. But try to understand my pov as wel
still, we're at square 1 . . .
got it
i want to share a video
do i share it directly here
just ask your question
the answer to that should be pretty obvious.
yes ofc, but apparently i came to know some people wont be able to see the video if i directly share it
in other server
thats the reason im asking is there a specific rule here to post a video
like u paste the code into an embedded one
like that
provided it is properly embedded it doesn't matter whether you share the video directly or a link. just ask your fucking question if you want help
i mean if we are going in a rude way then whats the use of a healthy discussion
if ur annoyed by it why not ignore the initial question
as opposed to arguing other nothing
because they actually want to help, but they're patience is thinning . . .
then practice some yoga
i would never go outta my way to add a derogatory term to someone's question
even if thats the most silly question
it has now been nearly 10 minutes since your initial pointless question and nobody here even knows what you are trying to get help with yet. this is entirely pointless, it is clear you would rather just spend time arguing about how to ask a question instead of just getting to the point and asking it.
oh, i'm good. i gave up a while ago . . . ☺️
i was speaking about the friendly box . . .
i was simply going to ask it once i get responded, u told its wrong, I accepted. Then I asked about the video. You told just ask ur fucking question. Does that make sense to you that if a person is kindly asking you so they dont get rule-spammed again?
anyways, i dont wanna argue more, im gonna post my question, if anyone is available any help is appreciated
#📖┃code-of-conduct no reaction gifs please
💀
Since yesterday (at least that I noticed) when I double click an error in my Console, it takes me to the wrong file/line number?
Share the error details and the file that it takes you to.
Takes me to CombatController line 441, which does call Inventory
the error is not hard to fix, it's just weird, I've noticed this a few times now, it just takes me to a random place instead of the error line
well that isn't really a random place, it is part of the stack trace for the error. it is odd that it takes you there though 🤔
but the actual error is on Inventory line 36
yeah this one is not random, think I had worse cases yesterday, but maybe it was similar
it worked perfecly for months, started noticing this only yesterday
why is bro a discord mod
Sounds like a new behavior to me. Did you update unity/vs extension/package maybe?
Problem: The coins are getting collision detection right and they are getting Deactivated properly (ig theres no array of coins thatswhy). Now Vehicles, Pickups are arrays. And When I collide with them, the collision doesnt seem to happen especially with vehicles. I am really confused about whats happening here. Also The Fps are dropping mid game
ObjectPooler script: https://hastebin.com/share/dubecaheji.csharp
My Normal Trigger Script format:
{
if(collision.gameObject.tag == "Coins")
{
scoreValue.score += 50;
//Destroy(collision.gameObject);
if (collision.gameObject != null)
{
op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
}
}
if (collision.gameObject.tag == "Enemy")
{
if (!hasShield)
{
hasCrashed = true;
crashCount++;
}
else
{
StartCoroutine(ActivateShield());
}
//Destroy(collision.gameObject);
if(collision.gameObject != null)
{
op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
}
}
}```
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
unity auto updates, I think there was a big update a week or two ago? might have been since then
unity does not auto update
even packages need to be updated manually in the package manager
ah maybe it asked then dunno lol
I know I updated unity a few weeks back with the new version control thingie
make sure your visual studio editor package (or the rider one if you use rider) is up to date and regenerate project files. then restart both unity and your code editor to see if that makes any difference
which part is confusing you? where do you suspect it goes wrong?
did u watch the video?
lol no
no thank you
they're helping the person before the mods come. once a gif comes in, others tend to spam right away . . .
better not try to help without going through the whole question tbh
remember that tomorrow when you come back to ask it again 😉
nope didn't fix it
dang, dunno what it is then 🤷♂️
are you sure you're double clicking the actual error message and not perhaps accidentally clicking the other line in the stack trace?
sure, ig people here are smarter, not everyone reads half the question and behaves like a d
try http://streamable.com to upload the video. it doesn't appear in chat; people have to download it in order to watch. not many will do that . . .
yeah i tried that, but this website doesnt open
shall i share it on google drive ?
it aint available in my country ig
I don't thing Google drive allows video embedding on discord. Try making your video smaller/shorter, such that discord displays it properly.
alright, thanks
Or maybe YouTube, I don't know.
haha yeah 😛
Problem: The coins are getting collision detection right and they are getting Deactivated properly (ig theres no array of coins thatswhy). Now Vehicles, Pickups are arrays. And When I collide with them, the collision doesnt seem to happen especially with vehicles. I am really confused about whats happening here. Also The Fps are dropping mid game
ObjectPooler script: https://hastebin.com/share/dubecaheji.csharp
My Normal Trigger Script format:
{
if(collision.gameObject.tag == "Coins")
{
scoreValue.score += 50;
//Destroy(collision.gameObject);
if (collision.gameObject != null)
{
op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
}
}
if (collision.gameObject.tag == "Enemy")
{
if (!hasShield)
{
hasCrashed = true;
crashCount++;
}
else
{
StartCoroutine(ActivateShield());
}
//Destroy(collision.gameObject);
if(collision.gameObject != null)
{
op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
}
}
}```
I have attached the video as well:
https://streamable.com/bfn2ac
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
make sure the vehicle collider is setup properly . . .
Hello, I am working on a game right now and I created two scenes. A Main Menu scene and my game scene. When I build the game from the main menu scene, I can press a start button that loads my game scene and properly runs the game. I then can pause while in the game and press the quit button, which properly loads my main menu. However, when I try to start the game again from my main menu, the game doesnt properly load and I get a bunch of errors about trying to access objects that have been destroyed
also, your code only check the "Coin" and "Enemy" tag. there is no "Vehicle" tag . . .
Do the trucks have trigger collider
The vehicles have 'Enemy' tag
it sounds like you probably have a DontDestroyOnLoad object (quite possible also a singleton) in your game scene, and when you return to the menu scene that object isn't destroyed but the objects it references are destroyed
then do this part: #💻┃code-beginner message
hey, i'm trying to use physics2d.istouchinglayers to no avail and i'm not sure why. i've looked through online forums and documentation, but i can't seem to find a solution.
colliders in question: circlecollider2d and polygoncollider2d
both colliders are on the same layer
any help would be greatly appreciated.
don't crosspost
sorry
yeah i fixed it, it works now
but why im facing fps drops?
even with object pooling which gives performance
what is a singleton, I dont have any objects expressly labeled DontDestroyOnLoad, but I honestly not sure I would know if I did
do you call DontDestroyOnLoad anywhere in your code?
no
you can also share the code for the object that is experiencing this issue
Does everything lag
If u watch the video, I am facing huge FPS drops and lags
kind of ig
I really dont know why is the lag happening and what is causing it to be
It looks fine to me what am I missing
When I was doing instantiation/destroy, then also I was facing this lag, And now with object pooling im facing same
let me share u the profiler info
If you’re moving the cars with rigibody
Make sure the part of the code that actually moves it is in fixed update
ok i will do that as well
but i m not using the rigidbody to move
im using transform.position
Then don’t do that
https://hastebin.com/share/axemuvuziy.csharp
This is the system script that is loaded when I press start in the menu. It properly generates a grid, however it does not perform the SetBoard function. Could it be because the tileList is not properly cleared?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
transform.position -= new Vector3(0, Speed * Time.deltaTime, 0);
it only applies to rigibody rly
oh
share the actual error you are receiving
MissingReferenceException: The object of type 'Tile' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Component.GetComponent[T] () (at <f7237cf7abef49bfbb552d7eb076e422>:0)
BattleSystems.GenerateGrid () (at Assets/Scripts/BattleSystems.cs:108)
BattleSystems.Start () (at Assets/Scripts/BattleSystems.cs:26)
MissingReferenceException: The object of type 'Enemy' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Tile.OnMouseEnter () (at Assets/Scripts/Tile.cs:22)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
my game is dropping from 60 fps to 30fps and even 15fps
ah, your tileList variable is static so it isn't a new instance when you enter the scene again, it's the same list and it contains the same elements that were in it before the scene was unloaded. is there a specific reason that list is static?
I believe I had it static because it made it easier to access from other scripts
lemme share the performance video
please do not use static just for easy referencing. learn how to get a reference to other objects properly. then you can remove the static modifier from that list and you won't experience this issue
Use the profiler to find the bottleneck/cause of the performance drop.
okay thank you
i recorded a video, its uploading right here
Hey I got a question. Im trying to use unity for my school finals project, and I am trying to create a teleporter that allows you to exit an area after all the enemies are gone. I get that the tag length has to be 0, but is there a way to differentiate between two rooms? Like have the enemy tag and a room number tag? if so how would i do that?
for what purpose you need tags on room
just keep an index
I will look into it, will come back if I cant find out how
ty
shouldn't be difficult, its just an integer
look into an int, come back with an integer . . .
ok. I am not too sure where I would find the seperation between rooms, but I think I can try it by having entities labeled "room #" and adding enemies on spawnable tiles at that entity on the arraylist, seperating them
sry if description is wonky, not too sure how to describe well
wdym where to find it?
the index is the separation
Can you state your problem a little more clearly?
If the rooms are stored in a list, then as navarone says, the index of the room can be used to point to different rooms. If they are not stored in a list, then you can tag game objects as Room1 and Room2 and similar
public class Room : MonoBehaviour
{
public int Index;
public void GetRoomInfo()
{
Debug.Log($"Is room #{Index}");
}
//Do more stuff with Room
}
I like that approach ^
mmm thats makes since ty. but I got one last question. Can tags have subtags or is that not a thing in unity?
eg you could store a list of enemies, so each room can have different amounts
not really you can only have 1 tag and you shold not rely on tags
start getting into a habit of learning Components
since unity is Component based
It is best practice to only use tags for edge cases
Forget about tags my friend.
They're extremely limited
Mostly a thing for prototyping
ok ty. I will look into it a lot more. Glad that i got all this help so fast
To determine if an object is of a certain type, you can check its layer, or TryGetComponent<ComponentType>()
So if you want to check if Room1 is empty, then perhaps you store a reference to the CurrentRoom in the teleporter, and the teleporter calls Room.IsEmpty(), and if it's true, allows the player to teleport, else does nothing.
yes ty. I was trying to reach this, but because I was new to unity, I thought the best way to do this was through tags. But I realize that I can do it differently. ty
Would you recommend getting the number of children under an enemy storage from the hierarchy?
Tags accomplish the same thing in a very hardcoded style, so it gets very difficult to scale
That can be one way to do it
I will look into trygetcomponent too
If a room has a GameObject container for Enemies, and it has zero children, that can imply that the room is empty
You can also draw a box over the room and check for enemy collisions
oh lmfao never thought of that
Or you can manually assign the enemies in the inspector to the Room in a List<Enemies> data structure and then check if the list is empty
oh yeah that makes since too