#💻┃code-beginner
1 messages · Page 462 of 1
thanks, i'll search about it
Do you mean just a straight up (mostly) random number or is there a specific set you're trying to work from
because all you need for that is to create a System.Random object and call Next. Then just check against a hashset until you get a new one
Hey all following brackeys Beginner tutorial, and im trying to add a function to my UI animation, however it keeps saying that it has no function name specified, even though it does
you probably added multiple animation events
one blank
When I move it around in my Animation tab its the only one
is there only 1 on that
yes, the little tab right below the 2 second mark, when I move it earlier theres nothing beneath
oh alr, is this the only animation you have ?
yes
I didn't quite understand, sorry. I need to make sure that every time I press a button, I get a number from 0 to 10, but these numbers can't be repeated.
In this case, it shouldn't be possible to press the button and receive the number 5 more than once, for example.
@open gull how many times are you taking numbers?
If it's just 1 to 10 then you don't need to care about performance, so just use a for loop to create a list, shuffle it and then take the last entry
queue or stack if you want to get fancy
fisher-yates if you want to get really fancy and/or care about performance
so I was working on something and my unity program crashed and now I lost all my progress from the last hour and half =/
is there a way to get it back?
depends, do you have version control and did you open unity yet after that?
you only lose scene stuff.
ctrl + s game weak
if you dont open the project again after crash you can recover, otherwise ur toast there
here's an example of what I mean ```private static System.Random rng = new System.Random();
static void Main(string[] args)
{
var set = new List<int>();
for (int i = 1; i < 11; i++)
set.Add(i);
//shuffle
RandomizeList(set);
string str = "";
foreach (var i in set)
str += " " + i.ToString();
Console.WriteLine(str);
}
static void RandomizeList(List<int> list)
{
for (int i = list.Count - 1; i > 0; i--)
{
var k = rng.Next(i + 1);
(list[k], list[i]) = (list[i], list[k]);
}
}```
output is something like 8 6 2 7 10 3 5 4 1 9
public int min = 0;
public int max = 11;
private HashSet<int> generatedNumbers = new HashSet<int>();
private int maxTries = 40000;
public int GenerateUniqueRandomNumber()
{
if (generatedNumbers.Count >= (max - min))
{
Debug.Log("All unique numbers have been generated.");
return -1;
}
int number;
int i = 0;
do
{
number = Random.Range(min, max);
i++;
Debug.Log("Count."+i);
} while (generatedNumbers.Contains(number) && i < maxTries);
generatedNumbers.Add(number);
return number;
}```
prob more performant using a hashset
I could be missing something but don't think so, this guarantees a unique value every time without a while loop
and no need to check
bunch of lists > hashset
maybe if you used an array
what bunch fo lists are you seeing?
it's one list
at the moment, 10, but I'll probably need more numbers in the future
Thank you very much
alr
``` is just tuple deconstruction, it's still one list. Is that what was throwing you
Thanks, I finally understood how it works 
great. For actually using it, I would recommend converting to a queue (or stack) to simplify plucking numbers from it. just something like ``` Queue<int> queue = new Queue<int>(set);
damn. kk looks like i'm fucked. I thought the editor was auto-saving my progress every time I started the game and tested stuff. my bad.
how do I go about avoiding this in the future. saving periodically obviously but are there any other steps I can take?
save periodically and set up some sort of version control if you haven't already so that not only are you saving the content, but also committing your changes so you can always revert and recover changes you've made
yeah with the scene thats about it, all you can do is remember to save when you see the *
version control your project 100%
I would be very grateful if someone could guide me with the following
I have a TMPro Dropbox and options are in a random order in the inspector
is there a way i can have the options displayed in an alphabetical order in the game??
does it change? maybe sort the list
Thanks will surely try
What have I done wrong with this Coroutine? Everything piece of this is tested and double checked but it wont trigger.
IEnumerator MeleeDistanceCheck()
{
while (UnitsInMelee() < formation.unitWidth * 0.5f)
{
formationMovement.MeleeAdjustmentMovement();
formationMovement.MeleeMove();
yield return new WaitForSeconds(5f);
}
}
the coroutine is started and stopped correctly, i've tested with multiple other conditions
and tested this condition in a debug line
keep in mind that if that condition is false then the coroutine will immediately end
So if UnitsInMelee() < formation.unitWidth * 0.5f is ever not true the coroutine automatically stops?
yes, why would it not stop? that loop simply does not happen if that condition is false which means it reaches the end of the method
I guess I am just going to do a timer
!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.
void Equip4()
{
hotbar1.color = new Color(144, 95, 95, 183);
hotbar2.color = Color.red;
hotbar3.color = Color.red;
hotbar4.color = Color.green;
hotbar5.color = Color.red;
hotbar6.color = Color.red;
hotbar7.color = Color.red;
hotbar8.color = Color.red;
hand_9.color = Color.red;
}
loops exist
uhh havent heard of that one yet here, not sure if theres a bot blocking it?
You could probably just use an array and reference certain instances depending on your necessary configuration
okay so hotbar1 is meant to be a darkred but when i run the game it is white, and i have no idea why
i ended up just doing color. red for the others because i coulndt figure it out, probably something stupidly simple that ive overlooked
i am right in thinking that it just takes the R G B and then opacity?
possibly, seems to be fine now
https://docs.unity3d.com/ScriptReference/Color.html
look at the values it takes, you are using very large values
between 0 and 1
did you add a f at the end of the number
0.02f for example
and also theres something called Color32 so you can use 0-255
instead of 0-1
i knew it would be something silly like that
you should read the error
i did it said couldnt turn double into float, double confused me
and i forgot abt the f at the end
sorry for wasting your guys' time
thank you 🙏🏾
way too late for that 😓
why 🤔
that doesnt really mean you cant refactor it to use loops
i suppose, but also being the beginner that i am
i thought id save properly learning loops til another day
the point of a beginner is.
you write shit code, you improve it, then you improve it 3 more times over the next few looks back at it
until your happy with the way the code is written
yep, and i am going to do so, today was all about working out ui for me
when i figure out loops yeah im gonna go back and refine it all
it definitely needs it
Anyone got any tips on how to about recreating the smoothing effects of the rigidbody interpolation mode when it is set to interpolate? I have my player's rigidbody interpolation mode set to none as of right now as it appears to remove physics mishaps that happened when interpolate or extrapolate were on. But since that also removes the smooth movement, how could I go about getting it back while keeping the rigidbody's interpolation mode to none? I do have the player's sprite object seperate to the rigidbody object.
you should say what those mishaps are, because you recreating the exact same system very likely wont solve anything.
https://docs.unity3d.com/ScriptReference/Rigidbody-interpolation.html
you can read what it does here, it just moves it every frame to make it look more smooth. Nothing should really change with the actual rigidbody movement
The physics mishaps are a bit niche and specific. One of them is relates to the player going around a loop (pretty much the same way it happens in 2d sonic games) but sometimes losing speed on the exit. This happens when interpolate is on, but I believe it never happens with extrapolate or none. Extrapolate does bring out a handful of other issues though.
Either way, my thought process is that if changing the interpolation mode in the rigidbody appears to mess with the physics, then just smoothing out the sprite itself without changing how the rigidbody updates could be a possible fix.
https://docs.unity3d.com/Manual/rigidbody-interpolation.html
actually this link has more info about it, but you wouldnt want extrapolate anyways.
tbh i dont think you want rigidbody movement for this at all
Maybe figure out why exactly it loses speed on the exit with interpolation. This shouldn't happen normally.
We can't help you with it unless you share more info on your setup and the way you move the character.
id say its more likely due to how you coded the rotation and such. Something is probably frame rate dependant
It probably would have been a better idea to not use a rigidbody for movement, but given I started this project so long ago, I sort of already have tons of code utilising the rigidbody, and I wouldn't want to switch it out for one issue.
I can try sharing what I think is relevant, since the player movement code is a bit too big to share all
Big code - more potential for bugs, so that's one.
I think you are correct on this. The loop issue specifically, happens when interpolate is on and at lower frames rates like 60 fps, but either becomes very rare or doesn't happen at all at higher frame rates like 240 fps. On the other hand, it just never happens when interpolation mode is off.
first place id look is if you are using the transform.position/rotation rather than rb. And if you are doing stuff in update rather than fixed update
It probably would be something relating to that. Is that something which should be impacted when changing rb interpolation from interpolate to none?
As in, turning on interpolate breaks physics when using transform.position/rotation?
No. It just breaks the interpolation. Returning the jittering
To be honest, unity physics are probably not great at maintaining velocity in scenarios like these(as is real life physics as well ). You might need your controller to account for that.
I probably should go into more detail about how I move the player. But I believe it's fully dependant on the rigidbody for moving around. The sprite on the other hand, moves to the player's position in the Update() via this line:
if (!isBeingCarried) sprite.transform.position = transform.position + transform.up * 0.25f; //Sprite position
This looks smooth and just fine when interpolate is on. But when interpolate is on, it seems to also create that one niche issue.
When interpolate is off, no issues appear to happen, but it does not look smooth, as expected.
Yea that does sound about right
Not sure why you'd do that, but it shouldn't be a problem imho.
Anyways, you need to make sure the velocity is maintained when the slope changes. Real physics would not allow you to make loops, unless you're on rails or something.
I move the sprite in that way because the player is in fact Sonic. When Sonic is curled into a ball and rolling around, his sprite does not rotate with his movement angle, and it has a rotation of 0. Since I relied on the rigidbody to move around loops and other curves, I have to later modify the sprite's vertical offset from Sonic to account for the slope angle, but anyhow that's unrelated.
I agree, I just find it strange this issue only seems to happen when interpolate is on
Question about unity Animator.
I currently run animations by doing animator.Play("animName")
this works fine so far but I want some smooth transition between various animations that happen through external events(what doesnt follow my code logic)
As well as something that would prevent specific animation from playing if another animation already is playing whats best way to handle it ?
Are you up for defining transition and using triggers?
As Bawsi mentioned, this behaviour is probably a consequence of you doing something illegal(in terms of physics), like running additional movement/rotation logic in update. That would indeed make a difference if the interpolation is enabled.
by triggers you refer to setting up parameters then having conditional transitions yes? if so I would rather avoid it as that creates messy spider web
I am looking at potentially having 20-40 animations so I would rather avoid anything that is hard to manage
Very well, I'll try and identity if the issue lies within Update.
Yeah unfortunately that's the "standard" way to use Animators
For smooth transition you could look .CrossFade instead of .Play
You'd have to manage own flag for preventing specific case
Maybe share your code instead. Then we probably could identify this or any other issue.
So I'm trying to find the position at the end of a ray that hasn't hit anything, a la my chart. How do i do this?
Same as how you did to Debug.DrawRay
if you use Ray you can use the GetPoint function
https://docs.unity3d.com/ScriptReference/Ray.GetPoint.html but yea easy enough to do it yourself.
origin + (direction * distance)
Should I share just code that affects physics? The script in question is responsible for a lot things regarding the player (mostly just the physics though), which after some time I learned may not always be the best idea. It may so be quite messy to someone who isn't me, since it doesn't really make use of a finite state machine for a lot of code, since I ran into so many niche bugs using the rigidbody.
Share the whole thing. We don't know what might actually be relevant and what not.
!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.
alright if you say so
Hey guys. Im having trouble in my game where I'm trying to spawn a collectable within a rectangle, but the player is inside the rectangle. if I just spawn it in randomly, without fail every single time, the collectable spawns in the middle of the rectangle. I can't just do a while loop that checks if the rectangle is a certain distance from the osition of the player and keep generating new random points until its far enough away because it is ALWAYS within 1 unit of the middle (and thus the player). This is what I've tried to do to fix this, but its still crashing unity because of an endless loop. I'm not sure what I can do. https://gdl.space/eruzasaqet.cpp
Welp here it is: https://paste.ofcode.org/GxPtujrXHggJxcMS9SvFS4
You''ll find what I believe is relevant within just UpdatePhysics() (function called by update()) and FixedUpdate()
I'm also decently new to Unity and programming as whole, so I expect much of my code may not follow common practices, or be clean/optimised.
There are also quite a few things in Update that do impact the physics, such as changing acceleration when standing on a certain surface, but even having moved those to FixedUpdate in the past temporarily, they never seemed to make any major differences to the physics.
For starters, you might want to limit the loop to a certain number of iterations, so that it doesn't freeze your game. Then you should debug the numbers to see why it's not ever outputting the numbers you expect.
As much as it may be a band aid solution, I think letting the rigidbody's interpolation mode be set to none is a valid option, since it appears to resolve any physics mishaps that were previously somewhat frame dependent.
very quickly skimmed through it, and yes you are using stuff in Update. first thing i notice is
Physics2D.OverlapBox(groundCheck.position which uses the interpolated position of the rb.
@void thicket & @eternal needle this helped a lot thanks :))))(
Honestly, I feel like debugging this code is gonna be nearly impossible.
But a definitely red flags and a possible cause of an issues with interpolation enabled is modifying any of the rb properties in update. This includes, position, velocity, gravity scale, adding forces, etc...
yeah interpolation shouldn't be modifying the outcome of the simulation at all
That does sound like a probable cause of the issue
Not probable. It is literally part of the issue
That's very fair, it is quite a messy script, and I only know how to navigate since I worked on it for a long time
interpolation doesn't make the simulation frame dependent though.
it takes two valid states, and visually interpolates between them. the physics engine is still running at a fixed tick rate
I can try doing something similar in which you taught me in the past, utilising something like:
Quaternion quatRotation = Quaternion.AngleAxis(rb.rotation, Vector3.forward);
Vector3 rightDirection = quatRotation * Vector3.right;
for ground checks etc
The issue is most likely me using variables from visually interpolated objects then?
Hey rq
I'm trying to create a method inside of a class that positions an enemy. It says that Component.transform needs an outside reference?
Doesn't transform exist in the API?
transform.position = new Vector3(Random.Range(-10,10), Random.Range(-10,10), 0);
also btw the class is created outside of start and update
I haven't read too much about your code because thats a lot of code...
why can't your update() logic run in fixedupdate()? for messing with the rigidbody?
This would be just getting a vector in a certain direction. But really a lot of it could be solved by moving the physics stuff to fixed update.
The issue is not knowing how to navigate it, but determining what parts could be affecting what and outputting important debug info.
Humans are very bad at comprehending(or rather holding in their heads) somewhat complex systems. You can't possibly account for everything going on in your code at the same time without letting some bugs get in it.
I do think a far amount of it could go in FixedUpdate()
Yea I meant just for replacing groundCheck.position by using rb.position - direction, I can try moving stuff into fixed update, though I have to some degree in the past too, without being able to see any important changes
Thanks for the insight
I have tried using Translate.position. using .translate instead, and checking the sutocorrect solutions. I also checked the Unity Scripting API and I don't know still
Also some other context that might be important:
It's in the class EnemyScript, the name of the script I;m editing
It's seperate from start and update. I tried adding in the code there and it didn't work
(This is C# btw)
public class Enemy
{
void Spawn()
{
transform.position = new Vector3(Random.Range(-10,10), Random.Range(-10,10), 0);
}
}
Here's what the full block looks like
And again it says that transform component doesn't exist
I'll try calling the UpdatePhysics() method in fixed update rather than update to see if anything changes without modifications at first
is that the whole code?
does your class not inherit from MonoBehaviour 🤔
No that's just what's inside the class
I think it does (It's inside MonoBehavior)
Well, there's no transform property defined in your class.
i mean do you have Enemy : MonoBehaviour?
No, it doesn't.
because thats what you WOULD need
OH.
Honestly I apologize for coming here for a noob mistake
at least I know now how to make a class inherit from another
When should I use MonoBehaviour?
well you should always use it
the question is when should you NOT use it
each class default creates WITH MonoBehaviour
MonoBehaviours are required for attaching to gameobjects
I guess never not because that's how I'm supposed to access Unity's components (guessing?)
you need MonoBehaviour to access stuff from it yeah, and also like said above.
you need MonoBehaviour to attatch scripts to game objects
UnityEngine.Object > Component > Behaviour > MonoBehaviour
MonoBehaviours inherit from component. They ARE components with more
Could not agree less with this advice
You should never default to using monobehavior unless something absolutely needs to be physically in a scene and act directly on a base unity component like a Camera. Ex. you want to catch collisions or implement something like IPointer
The vast majority of your logic does not need to be and shouldn't be in monobehaviors
Also note that that would spawn from -10 to 9 inclusive.
Use floats to have Range have an inclusive upper bound
can anyone explain me difference in Lists vs Array? If they are the same thing, why are there 2 things... if a string is a string; there is no other datatype like string.
they're not the same thing
lists can change the limit of items, array cant
C# list is more akin to what would be considered a dynamic array in other languages
if you make a list of 10, you can add 15.
if you make a array of 10, you can only add 10
So we use array to limit our values quantity, and lists to add infinite quantity
the difference is that arrays are fixed size, and lists are resizable
in other words, if you make an array the only way to change its size is to allocate an entirely new array. for a list you can call Add and Remove to dynamically change its size at runtime (and even Clear to completely clear it)
Haha, I was gonna write the same thing...
Oh I see... the List.Add Function is the main thing that makes List a List, We can't add values to Array at runtime, but Lists can do that
yeah for an array you can only set the value of an element thats already there
The other big benefit of list is access to Linq extensions
(this may also be a curse)
you can use those on arrays too, they are extensions for IEnumerable
Array implements that
Linq ❤️
i there a way to group multiple tiles on a tile map into one object, i want to rotate them together instead of separately.
what's the difference between a streamingasset and a random file on my computer? i'm trying to make code that's meant for streamingassets work with a file anywhere on my pc.
There's no difference other than the location
that's what i thought, thanks.
yeah i have no clue why the creator said that it would only work for streamingassets, i piped in a path to just a file on my computer into it and it worked fine
ty praetor
i need help with me code, i just need a movement
!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.
You need to configure your !ide so you have error highlighting
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
After it's configured it'll be really easy to spot the issue and code properly in future with more confidence
hi i am trying to make it so when i shoot a bullet left or right it knocks me back in the opposite direction the way the bullet is shot i think it is not working becuase some other code is overwriting it here is my whole script could someone help me https://gdl.space/yipogekixu.cs
im using addforce to do it and it works for up and down knockback but not horizontal knockback
body.AddForce(new Vector2(-knockbackForce, 0), ForceMode2D.Impulse);
that doesn't seem to take into account the direction of the bullet at all
its not based on the bullet
it should just move the player in the opposite direction depending on if i am facing right or not and if f is pressed
opposite direction of what?
but it doesn't include a direction in any calculation, just negative a variable
do i need a direction
i did the same code for up and down
and it works fine
and how would i add a direction
body.AddForce(new Vector2(0, knockbackUp), ForceMode2D.Impulse); thats my code for upwards knockback and it works
body.AddForce(new Vector2(knockbackForce, 0), ForceMode2D.Impulse); this is the code for knockback to the right
you should include all that in a single calculation instead of picking a direction in if statements
idk how to do that
and i have tried other instances of sending my character right and left and it doesn't work
i have a jump pad that works and when i went to make a boost pad out of the same code it did nothing (i changed the code to give a force on the x axis and it didn't work while the jump pad works fine)
i dont think it is a directional problem
and when i start the game and shoot immedient;y it works
only once
you seem to at least be trying, but you need a little work on design, it's a bit sloppy right now
and right after i walljump the knockback also works
I write this code so my walk forward and walk backward can play when i press the D and A key
if(animator != null)
{
if(Input.GetKeyDown(KeyCode.D))
{
animator.Play("Rifle Walk Forward");
}
else if(Input.GetKeyDown(KeyCode.A))
{
animator.Play("Rifle Walk Backward");
}
}
is it correct? Because when I tried to press the D key it doesn't play the animation
Debug your code.
Is the code even running?
Does it recognize the key press ?
I am making a Third person game. So I want the player to look at the direction of where the mouse is going to. Also I want that player can look a little bit up and down on Y axis but not rotate around it. I set it up but my rotation looks very weird and it doesn't look at where mouse is
{
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 targetPoint = hit.point;
Vector3 direction = targetPoint - player.position;
direction.y = 0f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
player.Rotation = Quaternion.Slerp(player.rotation, targetRotation, Time.deltaTime * 7f);
}
}```
Your slerp line is mixing up world space rotation with local rotation for one
changing that doesn't fix the main issue tho
@rich adder Im not sure how to apply this on my TMProdropdown list exactly
how would I made it so when I go up to a plane and press 'e', I get a first person view of the cockpit, and I can pilot the plane?
-
- Create an
enumwith move options for defaultPerson&Pilot
- Create an
-
- Create a
RaycastorSphereCastto determine whether the distance between the player and the plane is sufficient
- Create a
-
- In this case, if
Eis pressed, change theCamera's position for it to be inside of the plane, perpendicular to its window
- In this case, if
What specifically do you not know the meaning of?
In order to order TMP_Dropdown's options alphabetically, use LINQ's OrderBy method and convert the result to List
dropdown.options = dropdown.options.OrderBy(o => o).ToList();
Note that OrderByDescending, which orders the options by descending, exists
Enum is a data type to store a set of named constants
public enum State
{
None,
Person,
Pilot
}
@chilly prism Sounds like you need to !learn
You can name the constants however you want, and the previous message was not the best example
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hi guys, does anyone know how to assign an id to my prefabs at runtime? Didn't find any reliably way set the id in the prefab...
The only way I found is by spawning everything into the scene and referencing those, which could have some conflicts as any other reference to the prefab will remain unaffected, and besides that, it might have trouble if I ever search for anything in the scene...
But if you don't know input controls, you should do what SteveSmith has mentioned
understood
I am making a Third person game. So I want the player to look at the direction of where the mouse is going to. Also I want that player can look a little bit up and down on Y axis but not rotate around it. I set it up but my rotation looks very weird and it doesn't look at where mouse is
{
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 targetPoint = hit.point;
Vector3 direction = targetPoint - player.position;
direction.y = 0f;
Quaternion targetRotation = Quaternion.LookRotation(direction);
player.rotation = Quaternion.Slerp(player.rotation, targetRotation, Time.deltaTime * 7f);
}
}```
Why do you need to assign ids to the prefabs?
you do not need to repost your complete question.
As you have already been told your rotations are incorrect and on top of that your usage of Slerp is incorrect. So fix those issues first
Okay, so basically I use a registry system to map prefabs each to an id, and vice versa, reason is because I need to be able to save where is what in the world
Now, previously I assigned the ids manually, but for reasons like better moddability, convenience, etc, I decided to go for a more automated approach
Which comes to this problem- I can't seem to set the id by script at all
i just wanted to show the video... Also it wasn't a repost, I have posted new code
also i fixed the rotation one but still im facing weird rotation.
hi i have a problem with my player movement script sometime i can wall jump my wall and cant understand why my script: https://pastecode.io/s/ccmzxeuj
the problem:
How are you assigning IDs in the first place?
Each prefab that can be saved&loaded have a monobehaviour called SaveableObject, originally there's an int field for the id
I'm gonna be a grammarnazi, but that explanation is unintelligible.
Now I don't want to write the id manually anymore due to some annoying parts...
Especially since keeping track of order matters when I manually assign the ids
im french sry my problem is in the video i dont want wall jump
Now it's the Registry script, where on start it will Resource.LoadAll the prefabs and register them
Ok. So you can have a list of these prefabs on an SO or a some kind of MonoBehaviour manager. When you add a prefab to that list, assign a new id to it(the I'd could be equal to index in the list).
even in French there is such a thing as punctuation
Yes, that's the case indeed
But I'd very much prefer if the prefab knows it's own id too
Please use punctuation. I'm sure you have it in French as well.
If you don't want to jump when near the wall, you'd need to debug your code to see why it allows jumping there. Likely a condition for the jump is being satisfied when near a wall.
Yes, you can pass the id to the prefab at that timing as well.
i have an empty that detect ground maybe he detect wall too idk
Probably. How does it detect ground?
with a invisible circle return Physics2D.OverlapCircle(groundCheck.position, 0.02f, groundLayer);
Might want to use a raycast or a sphere cast instead.
How though? The workflow of registering as of right now is like this:
- Fetch from resources
- Cast to Gameobject
- Get SaveableObject component from said Gameobject
- Set id of the SaveableObject
- Assign to an array
Then you can check the normal of the hit point and not count it as ground when it's close to being horizontal.
ok i just reduce the size of the circle and now that work fine and yes raycast is maybe better i see a tutorial for making this
Why don't you use instance id?
Instead of fetching from resources, assign the prefabs to an array in an SO or a manager manually. Then it's the same as what you already do.
And programmatically you can just do the same via code.
I doubt instance id has much to do with this... I need to keep the reference across launches of the game
If you assign it straight in the inspector instead of fetching by resource, then setting variables in a prefab will be legit? Why would it be though?
Ah, fetching from resources is not specifically a problem in this case. I just think it's a bad practice. It should work as you do it now.
Sadly... It doesn't '^^
You might need to save the dirtied assets
So that the changes are actually saved to disk.
I wouldn't actually need to save it to disk normally... But I do need to keep the variable at the very least until loading another scene
Also editorUtility would mean that it'd only work in the unity editor which uh... Might cause some trouble '^^
You have to simply keep track of the prefabs, when the scene is changed or the game is relaunched?
Well... The reason for all this is that I need to save a prefab, and load it up whenever someone load that world, it can be across game relaunches or just in the same session
The id basically tells which prefab is to be loaded
So why not add a Behaviour to every prefab, which automatically assigns an id to it? Then, the script retrieves Components with this id from all required prefabs, and saves them to a json.
Assuming you mean a MonoBehaviour... Well, automatically assign an id to what?
If it is to the prefab, it seems to straight up fail as for some reason it remains 0, if it is per instance... Well, then the consequences is that I'll at the very least need to look up a dictionary whenever an instance is instantiated
Do you need to save instances or prefabs?
Prefabs
Then this approach is exactly what you need?
Retrieve a prefab from AssetDatabase and assign its id
Uh... Please test it the way you think works, might be missing the point as to how tricky changing variables in the prefab is...
Why is it tricky?
I figured that it sorta seems to work if the variable is serializable, and completely refuses to change when it's not
It makes it seem dangerously unpredictable
No?
I've got a feeling that if I build it, it might not work just like when it's not serializable
if the variable isnt serializable, what are you expecting it to do at all?
And even if it does, who knows if it doesn't work on one or another platform
It's set during runtime, not edit mode
just like scriptable objects, you cannot use assets to save data like that. doesnt matter if its serializable or not
in a build it wont work at all
I'm not trying to save the id across launches either
The prefab's variable can be changed, regardless of it being not serializable or private
It has to exist
I'm only trying to save it during one playthrough
Debug.Log?
I gotta go... Well, thanks for trying, though the issue is weird, trust me
You can try set up a small test and see for yourself
Debug.Log is one of the very first statments you should ever have written in Unity. If you do not know what that is read the docs or !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
everytime ive heard that, its just someone trying to do something they shouldnt be. Nothing about this is weird
I skimmed through the messages above and its somewhat unclear what you actually want.
string prefabPath = "Assets/MyPrefab.prefab";
GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
string id = prefab.GetComponent<IdSaver>().id;
And so, you can then simply save it to json?
No, it's the inverse of that...
And yes, that's the thing, I'm probably doing something that it's not meant for, however I don't know how it's meant to be done in the first place
So what's the problem to do the inverse version?
it doesnt look like you really described what the initial problem is, at least i couldnt see a proper question with it. This is an XY problem, you're asking how to do a questionable solution, not solve the problem
The problem is basically how to give each prefab an id during runtime, although it can alternatively be how to find a prefab's id during runtime
The registry does provide a nameToId dictionary, but I thought that it's for the best to avoid accessing a dictionary whenever I need the id
I'm busy putting together all necessary code to show the registry's functionalities, it'd probably make things clear
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.
again, this is not the problem. this is your attempted solution to a problem. I find literally 0 reason to why you'd need to assign an ID at runtime
The reason for that has been mentioned too, though... I need to write what prefab has been at a location into a file, and when loading the world, what prefab need to be placed at that location
nothing about that requires writing an ID at runtime. Just do it in editor
In a sandbox game
Hello! I'm making my first game (a side scroller) I made the player movement script now and I'm able to move horizontally. But my character is tilting and then falling on their side. Is it because of my capsule shape collider? How can I make them not fall?
In the editor, yep, definitely gonna go well
set the rotation constraints of the rigidbody
collider I meant collider :"
And I did mention that I started off writing numeric ids manually, however... It causes quite some trouble '^^
nothing about it being a sandbox game changes what i said. This is too vague for me, im not playing 20 questions honestly.
You dont need to write them manually, write it via script and use SetDirty to save it
i do the exact same thing, this isnt some weird impossible problem. And yes it definitely goes well
how are you moving your character?
like this (I'm following night runner's tutorial)
So you are using Rigidbody, in which case my previous comment stands
Well... That means that it's strictly in the editor, while I'm hesitant about restricting it to this as I wish to keep some modability to it, while having numeric ids could very well make things clash...
Yess, I'll try it. thank you
But yes, if it's not for that, it could very well be compiled in the editor without trouble
🤷♂️ thats a problem for the modders. give them the script if you want. Still, this changes nothing
modders know they have to jump through hoops a lot of the time
worry about getting your system actually working, no ones gonna be modding it if you dont actually publish it.
it's working just fine now :D_b thanks!
Ight... Well, since it looks like there's no clear answer to how I could assign ids the other way around, I guess that my choices are very limited now
Thank you guys, see ya
it looks like you were also given a few ways above by others on specifically how to assign a value at runtime. Im not sure what the problem really was, but you should show code if you're having coding troubles.
I did show the registry code
That one
oh, for some reason that link isnt loading for me. Not sure why
ah it loaded
im also not sure what the actual issue is, like does this code not work? really this just looks unneccesary to me. Id just drag these into some list/array and then assign the values at editor time.
If you or a modder wants to add a new ID, drag a new prefab into the array. or alternatively create some editor script which does this for you and assign an ID at the same time
Either:
Abandon the idea of this more complicated registry and go a very simple way, ditching some possibilities that might become a pain to change later on, primarily anything like content that may or may not exist
Instantiate prefabs into the scene or something, all references must be by registryId or registryName, and never use findGameobject style stuff
Prefabs don't have id, any everytime you wish to find id of a prefab, you have to fetch nameToId[registryName]
Eh... Yep, that's how it was done, except that it adds a lot of manual things to watch out about, there's a good point to it is that I'm usually so much into the technical part that I wouldn't have added a lot of content in the first place, even though I wish to have a lot of content one way or another, however contradicting that may be
from what i understand the issue is, the simplest solution id make is some list that holds all the prefabs and an int for the ID. Probably a scriptable object for this
You can use an editor script to simplify the whole process, where you just drag a prefab in and then the script tries to get the SaveableObject, and assign it a new ID.
What's your thought on the possiblity that it'd be a handicap later on tho?
Just curious since I'm always torn between choices thanks to that
A relatively performant, reasonably straightforward way, or a simple way that might have future troubles...
Definitely wouldnt call your current way relatively performant, or straightforward at all.
If you cant name a specific trouble with it, then why worry?
You could say the same about using unity. Why choose unity when it's possible it doesnt have a function you need? Might as well make your own game engine to ensure everything is there
Uhm, I don't think that my current way would've had any performance impact actually... As the registryName is only mapped per world startup, and the registryId is the thing that's actually used during runtime. So it's no more than a mapper that runs when joining or leaving the world
And since the code isn't homongous or reach beyond a small circle, I consider it very much so straightforward
However the second line is... Well, I think that it's true, or maybe not, I just never know if I should be concerned
You said relatively performant.
The option of already having them all assigned at editor time
vs
using resources to load all, then get component on each prefab to assign the value
Is not relatively performant at all.
Be concerned when you actually run into an issue. I dont see how there would be any issues. Any manual work can be avoided with editor scripts
Well, it's only during startup, I've been suggested to purely use string ids too, and I've read some stuff comparing numeric versus string ids
String id is definitely a performance hit throughout the game, while the registry was a startup thing
Hey guys, I'm not really sure what the issue is here, please help
You're trying to use generics here, but the class has nothing to do with generic...
you are missing the generic on your class declaration
I don't think that a monobehaviour can be generic in the first place tbh... Can it?
of couurse it can
i think it can no?
By the way, a generic here means that a class has a type declaration, like a list, you can choose what type it uses List<Type> list
Eh, I'm not quite sure about that... How do you give a Monobehaviour a type like it's some generic? Really uncertain how the inspector will interpret it...
Behold! A Generic monobehavior!
Well, I'm being jokish there, sorry xD
ohhhh, sokay, mistake on my part XD
But really, it just got invalidated

Works the same way you would use a regular generic class. You of course need to declare a class that uses it with a specific type
You are always giving a Monobehaviour a Type
class MyClass : MonoBehavious
is giving the Type MyClass to Monobehaviour
so
class MyClass : Singleton<MyClass>
does exactly the same thing
Yeaaah but just... Well... A monobehaviour wasn't meant to be generic as I was suspecting... The editor doesn't accept it
Thatd be a major surprise to everyone who already uses the same generic singleton implementation that is publicly available online
Eh... Well, fair point, although the second one made it... Not generic?
I mean, the baseclass is generic alright...
But during the inheritance there's nothing generic to it anymore
It's fixed to Singleton of a specific type
But yes, I overlooked that it could be inherited, sooo mistake on my part xD
I must admit I find it a stupid pattern to use, I mean inheritance is for mutable parent classes and something that is immutable like the singleton pattern (also badly implemented in this case) is just a waste of space
Well... True, singletons are typically just a static variable of itself, and assigning itself to the static variable on awake, there's usually no reason to generalize them
I used it in my registries only cus it's pretty lengthy and repeatedly used
Unity has a generic singleton implementation. You can just inherit it and use it as is.
ok so i was jus doing some things on unity and all of a sudden no buttons work. none work
i dont have any code that does that
I think that that'd not even be a code question anymore... Right?
Oh, you mean in-game ui?
yep
Check the event system component
It might be using the wrong input system or not exist in the first place
Otherwise there might be a panel blocking it, maybe you added a transition screen or something?
nope
Both are normal?
did you delete the Event System?
I mean, you checked that you have an event system like this?
Might look different depending on which you're using
It should be added automatically when you add a canvas.
If you removed it, then pointer events wouldn't work.
using System.Collections;
public class CompleteCameraController : MonoBehaviour {
public GameObject player;
private Vector3 offset;
// Initialisation
void Start ()
{
offset = transform.position - player.transform.position;
}
void LateUpdate ()
{
transform.position = player.transform.position + offset;
}
}```
why i have blue bar in my screen since i put the following camera
I'm not 100% sure if it's the case in the video, but I have a suspicion you're seeing the gap between sprites at times
I'm not sure how it's fixed, sorry, this page looks like it's just the thing you need though
https://blog.terresquall.com/2023/03/how-to-fix-gaps-in-your-tiles-in-unitys-2d-tilemaps/
I forgot to ping haha
Answer's above
hey, when I have a public Text loseText
when i try to use loseText.enabled = true; it doesnt show it on screen, i resized and positioned it. . . i even clicked on the Check mark on top in the inspector
i have using UnityEngine.UI; ready too
ty that my problem i gonna check that
Behaviour.enabled enables the Behavior, so setting it to true should check the boolean next to the Text component. Are you sure you're not confusing it with enabling the GameObject?
oh sorry, im supposed to use isActive? i think i get it . . . give me a min to try to fix it i fixed it. . . i used GameObject instead of Text and IsActive instead of Enabled
thanks
so i patch the problem with a pixel perfect camera but now my camera shaking when i move that not smooth at all
The gap between sprite appears because of your Pixel art.
The thing is that Unity should only render it correctly with the appropriate screen size.
Say, if you have 16:9 32x32 sprites, the appropriate resolutions for you are 512x288, 1024x576, 1536x864 etc.
To deal with it, consider adding the Pixel Perfect Camera component to your Camera, and adjusting Asset pixels per unit
You should use gameObject.activeSelf or gameObject.activeInHierarchy
idk what is that, or how to use it. . i just used GamgObject.isActive(true); and it worked
What do you mean by "idk what is that". Use gameObject.activeSelf instead.
okay
i will try
GameObject.isActive(true) doesn't even exist
it worked for me tho
Show the code
You meant gameObject.active?
It enables the GameObject
ye thats what i wanted
Yes, that's a correct approach for assignment
that the same when i adjust asset pixel per unit
ok that work now (dont understand why but that work)
ty
Hi all! I'm trying to find the Restart game function, as stated in the Game Maker's tutorial. But I can't. What should I do?
show the code where you declare the RestartGame method
hey how can make the player more slow than this?
you have not saved your code
Thank you!! Its working!
The subtraction you're doing doesn't make much sense
whats thats
Your walk and sprint values should be class fields so you can edit them from the inspector, not local variables which only exist in the Movement method . . .
does make any def?
that
Subtraction is -
The calculation you're doing doesn't make much sense
well its working but its to fast
So the movement code is hard to decipher and hard to reason about
Most likely because of the weird subtraction logic you are using
how about i make it + (●'◡'●)
same thing
How about you think about your code and write something that makes sense instead of guessing
hmm then lets make it *
quick question, I want to draw a ray for debugging, but I cant use + and I need it to be the length of a raycast. What else can I do?
Debug.DrawRay(transform.position, Vector3.down * playerHeight * 0.5f, Color.black);
Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.5f)
Parenthesize or reorder the operations so the addition is accepted:
Vector3.down * (playerHeight * 0.5f + 0.5f)
thx
The issue with your current code is that, as operations are evaluated left-to-right (as you only have multiplications), Vector3.down * playerHeight is evaluated first, which produces a vector, which is then multiplied by 0.5f, which produces a vector, and you can't add a vector and a float.
When you reorder the operation by adding parentheses, it will add all the floats first, before multiplying it with the vector
Show the bird's inspector in Unity
birdIsAlive is false
!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.
hey, can someone help me with this code? https://hastebin.com/share/inubatovob.csharp
why is my cube rotating because of this? he moves on the Z but he rotates while moving..
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Physics, the friction causes that behavior
huh? what do u mean? its not my code but its because of the cube object physics?
Yeah the physics engine interprets the friction between the cube and the ground and generates some torque
You can freeze the rotation from the Rigidbody's Inspector if you don't want that
aaah i see yess! thank u very much. i was so confused lol i thought i had created some sort of animation haha
What should I do if I want to store important game files in an external folder? For example, save data. Where should I write it to? I want to make sure it's a place that will be there both before and after I build
Like save data, level data, etc
i think it was this https://docs.unity3d.com/ScriptReference/Application-dataPath.html
or maybe it was something else im not sure exactly
you can use that
oh sick ty
no it was this i think https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html
ah check them both out and see
Application.streamingAssetsPath is the only path that works for you. Trouble is on most platforms it is Read Only at run time
persistentDataPath is fine
persistentDataPath is not included in a build so would be unsuitable for level data
Yeah this is my issue
what is your target platform?
Put them in streaming assets and copy them to persistent Data Path at runtime
then streamingAssetsPath is OK, it is Read/Write on windows
Are you meant to store level desingn data?
well, more accurately i'm storing .jsons with information about levels
and some files to go along with it
Is this user specific or something every user shares same value
the player uploads two files and my code creates a json, then my code is going to zip them and save them. but i'm not sure where i should save the zipped file
every user makes their own stuff
i need this to work both in the editor (so i can test) and in builds
So just persistentDataPath?
That’s R/W, just the data is not with the game when you deploy
this looks like it should work
yeah that's fine
i just need the folder itself to be there when deployed
i know this code isnt working and cant ever work but why? can someone explain why it doesnt work? is it because the transform.localrotation = Quaternion.Eular(mouseX, mouseY, 0f) is always setting the rotation to the input of your mouse so if u move it it will set it to the input of your mouse and if u stop your mouse it sets it back to 0?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The mouse input data you're reading is the change in mouse position since last frame
So it makes no sense to use it in this way
the mouse axes are the changes in the mouse's position, so you need to treat them as a change and not as a set position
Axis is delta
Looks like you want to accumulate the value
transform.Rotate(mouseY, MouseX, 0);
hey i was following this (https://www.youtube.com/watch?v=kXbQMhwj5Uc) youtube tutorial on how to implement a gun system in unity. i am a complete beginner, this is my first time trying to make a game, and i am at 6:24 but nothing is being output into the console. here is a screenshot of my code if you can find anything wrong with it.
I present to you my longest video yet. Sorry for all the mistakes in the video, I usually don't make such long videos.
In this video, I teach you how to create a simple weapon system. In future episodes, we'll add weapon switching, and visual/sound effects.
PROJECT LINK: https://github.com/Plai-Dev/weapon-system/
Like & Subscribe!
Timestamps...
Make sure Shoot() is being executed by placing another log in it, at the very beginning so it's not guarded by any if statements.
Looks to me like you're missing some code in 'Update'
Ohg nm, ignore what I just said.
that is all the tutorial is telling me to do at the moment. visual studio is currently updating but once its done i can show you the code for playershoot (another c# script which is meant to call the shoot function(i think))
Other code isn't necessary at the moment, debug first so you can pinpoint where the issue exactly is
ok, i was just thinking that maybe the bug is in that script instead
but like i said this is my first time
It could be as simple as things not having colliders for the raycast to interact with. Might be worth taking the Raycast line out of the if statements in the first instance to see if your raycast is actually working?
im sorry if this comes across as a silly question but how would i do that?
Too fast, take it step by step. Maybe none of the code is being executed right now, so no need to deploy the full debugging tools yet
Okay, move the log further into the if statements until you don't get it anymore to see which one is failing
found the issue, the gun had no ammo in it 😑
lol turns out it wasn't resetting when i stopped playtesting which i thought it did
If it's data from a ScriptableObject, it most likely won't reset until you restart the Editor (in the Editor) or the game (built executable)
yeah i fixed this by instead storing it as a variable and setting it to the magsize in the start function
Hi all,
So, I have this little bit of code that populates a UI panel with 'starting' values
public void PopulateResources()
{
foreach(AvailableComponents availableComponent in availableComponentList) {
GameObject newAvailableComponentPrefab = Instantiate(availableItemPrefab, componentParentPanel.transform);
Image resourceIcon = newAvailableComponentPrefab.transform.GetChild(0).GetComponent<Image>();
Text resourceName = newAvailableComponentPrefab.transform.GetChild(1).GetComponent<Text>();
Text resourceAmount = newAvailableComponentPrefab.transform.GetChild(2).GetComponent<Text>();
resourceName.text = availableComponent.componentDataContainer.componentName;
resourceAmount.text = availableComponent.componentAmount.ToString();
}
}
Because I need to access and change some of this data and display in the UI (specifically the resourceAmount), I was wondering if it would be best to add each GameObject that I'm instantiating to a list and then referencing the list later to get the various 'bits' of the prefab? Or would there be a better way?
Add a script to the prefab which contains all the references and Instantiate that script, you can then pass that around if you need to
Forgive the potential stupidity, but how would I then reference a specific prefab that I've spawned and change it's values from an 'UpdateResourceCount' method? Sorry, drawing a blank. lol.
when you spawn the script using the Instantiate method it returns a reference to the instantiated version of the script, i.e. the one on the instantiated prefab
is there a way to disable / enable new InputSystem's callbacks in a condition? (I need to disable 2 callbacks (one regarding to move and one regarding to camera movement), when the player hits the escape button (a pause menu should show itself)) The reason is, when the player hits the escape and pause menu shows, the user can still move with the camera and the player body
I'm so sorry, I'm still not really following.
For example, if I were to use a list my UpdateResourceCount() method would be something like....(simplified and missing things out but you get the idea)
UpdateResourceCount(int resourceIndex, int resourceAmountAdjustmentAmount) {
//Update the componentAmount value here
instantiatedPrefabList(resourceIndex).componentAmount + resourceAmountAdjustmentAmount;
//Then do the UI Update stuff
}
I'm not sure how to do the same thing just referencing the script on the specific prefab that needs updating (if that makes any sense?)
in a condition or not is irrelevant. If you can locate the correct InputAction in your Map you can enable/disable it
gamers, whats the best way to prevent this from happening when using a sphere collider for collision
essentially i can climb stuff that u realistically shouldnt climb
Usually you wouldn't use a sphere collider for the body of the car afaik, you'd have your wheel colliders and use either a box or mesh collider for the body.
idk if wheel colliders are good for arcade physics
no where near enough context for this to make sense. btw your original foreach does not make a lot of sense either,
No wait, I see what you are doing there
Is there a way to programmatically decrease shadow quality in URP? I have baked shadows using bakery and use mixed for my character and enemies.
I want to add a graphics settings allowing to have both realtime and baked on, only baked (disable all realtime) and another option to disable all shadows (realtime and baked)
Okay, here is the full code.
https://hastebin.com/share/agoqomovih.csharp
In simple terms it's essentially an inventory system (space station construction/management game)
The player will be able to 'craft' components (that will then be used to build Modules onto the station), so I'm working on populating/updating the component inventory amount.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Screenshot for reference.
And just to be extra annoying. Another screenshot showing my 'AvailableComponentList'
Create a new script MyScript like
public class MyScript : MonoBewhaviour {
public Image resourceIcon;
public Text resourceName;
public Text resourceAmount
}
add it to availableItemPrefab and fill the references in the inspector. Change the type of availableItemPrefab to MyScript
then your code becomes
MyScript newAvailableComponentPrefab = Instantiate(availableItemPrefab, componentParentPanel.transform);
newAvailableComponentPrefab.resourceName.text = availableComponent.componentDataContainer.componentName;
newAvailableComponentPrefab.resourceAmount.text = availableComponent.componentAmount.ToString();
@ruby python
uh, for some reason a scene works perfectly fine in editor while when builded it looks like this
would anyone know why this might be happening xd
As we don't know what it looks like in the editor how can we tell the difference?
Okay cool, yeah I understand that part, thank you. The thing I'm trying to wrap my head around is how to then reference a single prefab that's been spawned (for example if you look at the first image I posted, if I want to update the 'Metal Girder' amount)
Not a coding question. #💻┃unity-talk
If you're using multiple scenes, make sure you've actually added them to the build settings. Otherwise, make a development build and see if there are errors being thrown.
you would need to add the spawned MyScripts to a List or Dictionary in order to keep the references
Riiight okay. Yeah, that was my original question about using a list. Sorry, I don't think I explained it very well. Thank you sparing the time though. Very much appreciated 🙂
i take back what i said about it being quick and simple.. took way too much trial and error
so the turret Base lerps and rotates on the y axis until it reaches desired position then the turret itself rotates on the local X/Y axis to the desired point?
yeah i used to do that in garrys mod lmao
but once u start breaking it in pieces and having to recombine
it got challenging
check out the thread for the failed results lol
im gonna try to add predictive aiming soon.. (ive already realized i can't add it to the turret) the math is too hardcoded.
soo imma have the projectile *project where it will actually be in X amount of seconds) or w/e
and get the distance from the turret.. and then the turret will track that object instead
{
Debug.Log("Starting animation");
TextBubble.transform.localScale = new Vector3(1.3f, 0.7f, 1f);
yield return new WaitForSeconds(0.25f);
TextBubble.transform.localScale = new Vector3(0.9f, 1.3f, 1f);
yield return new WaitForSeconds(0.25f);
TextBubble.transform.localScale = new Vector3(1f, 1f, 1f);
Debug.Log("Finished animation");
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "TalkingCollider");
{
if (other.gameObject.name == "1");
{
GiveMeASecond();
}
}
}```
The last line (`GiveMeASecond();`) that actually is suppost to do something literally does... nothing.
Why?
That is not how you start a coroutine
alr
always look at docs
you obviously did not read the docs you were linked to. StartCoroutine
I literally had no idea what a coroutine is
so uh
I'mma get to reading
thats why there are docs, you you can find out and learn
Looking up unity IEnumerator would lead you to coroutines
Anyone know why a demo project (QuizU) isnt loading the whole solution *in visual studio when I doubleclick on a script in the asset browser and is just loading the individual file? Other projects I have arent behaving this way
how accurate is fixedupdate at running on a constant interval? i'm doing some stuff with MIDIs, and i have a midi being played. I'm using fixed update to constantly move forward a character based on how much time has passed in the MIDI. however, it's pretty inconsistent, with anywhere from 8-16 ticks passing each fixed update. the song's tempo isn't changing, so if it truly is fixed, wouldn't it be the same amount passed each update?
It is TRYING to go as close to the rate as possible, but it will almost always be slightly off. This is inherent due to the varying rates of update. Only one thing can run at a time on the main thread
Unity is single threaded so FixedUpdate can only be as accurate as the deltatime of the intervening frames allows it to be
@weak cedar Do not take a video of your screen with your phone
Why does it go back a little when it collides
"move" is on update
Is this the rigth way to do this because im not getting any logs?
It is trying to get outside the collider I guess
I don't think Move respects physics as much as other methods, but first try setting collision to continuous in the inspector
make sure one of the colliding objects has a rigidbody
The code is likely not the issue at all
the same
and the colliders are set up properly
check collision.collider
I dont know how i forgot. But Thanks!
they said they're not getting any logs, including the ones outside of the if statement. therefore, it's not an issue with parameters, nor can they check parameters
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a 3D Rigidbody on at least one of them
(Stolen from digiholic)
yeah for sure
Found a solution and I'm quite surprised it is the way that it is by default for this. The Unity Registry asset "Visual Studio Editor" was not installed in the demo project. Installed and it works as expected now
Would using velocity respect physics more?
Honestly, what is the issue? It looks like it only moves back to avoid penetrating the other cube
Do you WANT it to penetrate?
is there a way i could run the code that deals with syncing the music on a separate thread? there might be issues with race scenarios but i don't think anything accesses this specific field besides the code i'm trying to write
I don't want it moving back
Or do you want it to just not spin if it can't
I implemented the spin myself so it matches with the joystick's movement
Ok, so do you want it to penetrate or just not spin?
Because the three choices are those or move back
there's a rigidbody method that moves stuff with physics in mind iirc
any ideas why this is not showing in the inspector?
I thought rb move would do so
make sure it's serializable
oh you are using rb.move, mb
you would probably need to take it completely outside of Unity to do that, if you can do that then yes
thought it was transform.translate
Velocity or addforce will do better but you also want physics materials. And you need to decide which of the three options will happen. Penetrate, prevent movement, or bounce back
I just don't want the slight move-back
i already have the code that plays the music on a separate thread with some dll stuff, so that might honestly be the issue, the music itself isn't synced with unity
Ok, well as I have said, you have to decide what it does INSTEAD
If you spin the cube and it is going to go INSIDE the other cube, what should happen
then it should be simple to sync a seperate thread yourself
Go inside the cube? Not rotate at all? Or bounce back?
not sure what you mean by that when its already using [SerializeField]
oh I see what you mean wait let me disable the rotation method
serialize field will try to serialize it if the object is serializable
if it's not serializable, it won't serialize
are these your own classes?
I disabled the rotation and it still bounces back a little
the PlayerInputActions is a generated class from the new input system
did you write it? i'm looking through the new input system docs and i can't find that class
It is the generated c# class from the input actions asset. You name it, but it is made by unity
ah
I honestly do not see it happening except when you rotate
Is it... happening in this video?
it is, you can look at the x position of the cube
when the cube is moving, it's 2.01 something, when it's let go, it snaps to 2
yes, its really really slight
So the .01 movement is really... an issue?
hurts my eyes, so yes
Ok, well that is just a normal thing that happens with physics 🤷♂️
I have 0 ideas how to deal with it except redoing your own physics with raycasting or other spatial queries
You can try velocity or addforce as mentioned above
It shouldn't be getting pass 2
I'm guessing this is normal with rb Move, I'll try addforce
You will likely experience some of it still, but hopefully less? 🤷♂️
It is completely invisible to my eyes
To avoid it completely, use spatial queries
Do you have any console errors?
yo, i need to learn how to code.... tutorials on youtube dont help at all!
!learn well dont use YT then
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Youtube is terrible for starting imo
ya, youtube is more for niche tutorials/systems
so what are yalll makin?
greetings brothers , i am new to unity and wanna enhance my experience by game developing but theres one tiny problem .. I dont know how to code at all , is there any way that theres a built in code help thing in unity to atleast help in basic functions ?
fps fallout clone
im makin vr tf2
!docs
ohh.. neet lol
I don't make stuff; I break stuff . . .
look at visual scripting
BOLT ... will have most of hte basics
you'll still end up needing to learn how code flows
A wise heavy man once said - "All of you are DEAD!"
BOLT ? You are behind the times, lol
ohh am i? i dont stay updated with visual scripting lol
ill look for everything u guys said , Thank u very much !
Unity bought BOLT some years ago
BOLT? Love the respect . . .
but its still called BOLT right?
no, it's called Visual Scripting
why yall saying BOLT in all caps?
makes it sexier
oh aight
but turns out bolt has been bought by unity.. so its just alled Visual Scripting
lame
i knew they bought it.. didnt know they rebranded it
Which one looks more powerful: Bolt or BOLT?
⚡ BOLT
b o l t - that looks powerful
btw for a starter like me , is 2d or 3d a good option ? i know 2d is simple and 3d bit complex but wanna know from experienced ppl
setting velocity solved it
i personally start with 3D
Either is good. Neither is more complex
Go with what you want
aka bolt
i love making maps in 3d unity
wanna make me a couple? 😈
I wouldn't say one of them is more complex because it really depends on what you do, but I personally rather 2d
what do u want?
Gotcha , thank u both .. ill go and collect some great free assests and try experimenting
im just kidden bro.. im doing a open-world-esque game... it'd be overwhelming
oh aight
soo far soo good
yo i feel bad for whoever had to make the "sons of the forest" map
👉 👈 Free for ur brother here , right 😋
ik it was a team but its so detailed
Valheim, 7 days to die and Genshin Impact too
did you figure it out ? You just apply the method to the list of strings
i dont like genshin impact that much, mostly pedos play that game 💀
not judgin ofc
lol, i was just lookin over a list.. can't say ive played any of em
Hi! I want to fix 2D camera width to 12 units on screen, and wrote this code:
// cameraWidth = 4000 (random number)
var currentWidth = camera.pixelWidth;
camera.orthographicSize = cameraWidth / currentWidth;
Which worked in the editor, but when I built it, it was not 12 units.
How do I do it properly?
Both are the same; the only difference I see is the setup. 2d is easier to create animations from sprite sheets but you'll need to learn how to use tilemaps
With 3d, you can import tons of animations from Mixamo, but you have to learn the animator, blending, and states.
what is the short cut key to take screenshot on laptop ?
you have singlehandedly fixed my code a quarter million times, you do indeed make stuff
print screen
Win + Shift + S is the superior way
heres a plot twist, i AM spawn camp games!!!!
Ah gotcha , ill search for Mixamo
i'll sue you bro
You will sue yourself??!!
Thank u very much !
most likely i'll sue ur parents.. since ur probably not tax payer age yet
no problem 🙂
Youll sue your own parents?!!!!
win + shift + s allows u to snip only the parts of hte csreen u want..
aight ima stop
Ah , thanks alot .. i really appreciate ur help
Hello every one, does any body knows why when i use this code.
print(Input.GetAxisRaw("Horizontal"));
I always get -1 when Game window is selected but when is unselected it returns 0?
Im using a keyboard for input
im bored
when the game is unselected (its not focused)
ur not getting any inputs
so therfor (0)
if ur getting -1.. that means ur S key or ur Arrow Down key is stuck 🤪
magic

I would advise you to stop posting irrelevant shit before a mod comes down on you
tf did i do bruh
Firstly I ain't your bro, Secondly look at your last few posts
Humm... I tried with another keyboard but still having the same issue
it aint hurtin anyone
This is not a place for you to satisfy your boredom. Go to some social server that has an off topic channel.
This is not a social server, there is NO off topic allowed
you dont have a gamepad plugged in do you?
Nope
share your code..
This is everything 😵💫 🤣
if its that deep than just report me, dont whine and bitch about it
ill go
must be some key thats getting inputs when it shouldnt 🤔
OK, As you wish <@&502884371011731486>
ohh and before i said S key or down arrow.. u said 'Horizontal'
so its more likely ur A key or Left Arrow key
debug "Vertical" too while ur at it and see if its zero or -1
i believe Horizontal is A or D
ya, lol.. had a brain fart
most times i seen this happen it was because someone had a gamepad plugged in with stick drift..
never seen it w/ no gamepad was plugged in.
It is -1 too
do you have any controllers or keyboard plugged in
okay 
@queen adder This isn't the server for random crap. Keep messages relevant.
if you do it sounds like the controller is drifting to the bottom left
BIG drift too
u could debug Input.Axis w/o the Raw part
and it'd give u a more accurate representation
actually a small drift would affect it to
as long as the dead zones of the controller are small
for Raw? i'd think it had to be over halfway to the edge
it relys on controller deadzone i believe
i could be wrong
I made sure to have only the keyboard connected and tested with two different ones.
I'll restar my pc
i probably shouldnt have said keyboard since they dont really have drift, unless the A and S key is stuck
Mouse could be fucked/ Maybe?
im not sure mouse affects Horizontal or Vertical
Laptop+TouchPad?
sure it does
you would know if the keys were stuck though
isnt mouse connected with Mouse X/Y
#💻┃code-beginner message
look at the Type setting
It is extremely odd though
Guys , whats this for ?
organization
Hey all whats the correct string for left control, this doesnt work
Keycode.LeftControl i think nvm thats KeyCode
should i take it ?
ohh, is left ctrl not a button
not sure what the string is for button
it's a keyboard key
i typically use GetKeyDown(Keycode.LeftControl);
Humm tried without Mouse and still having that error
I tried with this code and it is going well, so keyboard is okay
`float horizontal = 0;
if (Input.GetKey(KeyCode.A)) horizontal = -1;
if (Input.GetKey(KeyCode.D)) horizontal = 1;
print(horizontal);`
tried this and in debug isnt showing that isSprinting is true when lctrl is down
u can use the Input analysis window to see ur inputs
i cant remember if u have to have the new-input system enabled to view it tho
i dont even have the analysis in my winow tab so
ya its probably b/c i have the new input system installed
and my project set to use both of them
you have to have analysis in the window tab..
b/c how else would u run the profiler?
yeah i do it wasnt in alphabetical, thats my fault, but it doesnt have the input debugger
ahh okay
i wonder what happens if u use Keycode.LeftArrow and RightArrow
the -1 must be coming from somewhere
So i fixed it by just getting rid of the down, now its just input.GetKey
ohh yea i was mixing u up with the other guy with input problems
GetKeyDown = the frame it was presed on
GetKey is all the frames its held on
its fine, thanks for the help
It behaves the same as A and D 😦
Could it be that I installed it incorrectly or that there was a problem during the installation of Unity?
Also tried with different versions
id have to research
im trying to add a stamina bar to my game where if you dash, it sets it to zero and then it regenerates but for some reason it wont work
which part is not working ?
Thanks, this problem is frustrating 
the fillamount doesent work
fillAmount is 0-1
oh

i think ill die even before i reach to the programming part by watching u guys
just divide by 100
almost very much lmao
remove the -
float fillAmount = currentStamina / 100;
staminaBar.fillAmount = fillAmount;```
Think for a second. You're subtracting from the stamina because they took damage, so naturally not that one.
what are these lines for ?
Whereas you're assigning a value to fill amount, but giving it a - sign. You don't want a negative value, of course.
they're closing braces.. theres 1 for every opening brace
time for c# courses
like we have to add em in start and as well as at the end of each programming point for it to work ?
function()
{
if(thisthing)
{
// do something
}
}```
Programming point?
You should do this
https://www.w3schools.com/cs/index.php
And then this
https://learn.unity.com/pathways
new to this so idk what to call em lol
They are called scopes
But I think you are thinking of the wrong thing when talking about programming points
This isn't the place to ask extremely basic questions, that's not how you learn. Do the tutorials/resources and actually learn.
have 2 courses in my yt to watch , but its better if i ask actuall ppl as well as u guys are experienced and i can learn alot from video and u guys
It's not. Extreme hand-holding is not for this server. If you want someone to mentor you, you'll have to find that.
Do not use youtube, especially if they are Brackeys or Code Monkey
#💻┃code-beginner message
yea
Is your image set up to work with fill?
how do you do that
🥲
How did you do that?
wdym
How was your image component configured?
well
il check it right away , thanks
It isn't. You need to give it a source image, and change the type to fill.
like this?
can yall hop in wild streaming and show me rq i dont really understand
Best way to learn Unity is through Pathways courses on Unity Learn. Learning C# basics first would be very beneficial as well. Also with rare exception of one or two very comprehensive course series on YouTube you would be better off finding an interactive or written course with practical examples and exercises.
download that plain sprite i sent, plug in the image component as sprite, switch it to fill mode in the inspector
ok thx
Ignore this...
oml it works now tysm
thank u very much , a brother just sended me link to pathways and i am currently looking it 😋 ... idk why brother Osteel got that mad on me for asking .. i am literal newbie so idk what to do and like talking to u guys , u guys helped me with pathways and other learning site .. From there ill try my best to learn .. God bless u ☺️
Osteel did not get mad. Just said something completely accurate and correct
😅 oh , i thought i made brother mad
I am getting an error its in the screenshot this used to work fine now it doesnt no idea why anybody know why its with the Input.
{
public float speed = 5.0f;
public float speedx;
public float speedY;
public float Health = 10.0f;
Rigidbody2D rb;
private Vector2 spawnLoc;
public Transform player;
public Vector2 playerPosition;
public GameObject transition;
public GameObject enemySpawner;
// Start is called before the first frame update
void Start()
{
spawnLoc = new Vector2 (-7, 1);
Health = 10;
rb = GetComponent<Rigidbody2D>();
TransitionScript script = transition.GetComponent<TransitionScript>();
EnemySpawner enemyspawner = enemySpawner.GetComponent<EnemySpawner>();
}
// Update is called once per frame
void Update()
{
speedx = Input.GetAxisRaw("Horizontal") * speed;
speedY = Input.GetAxisRaw("Vertical") * speed;
rb.velocity = new Vector2 (speedx, speedY);
getPlayerPos();
if (transform.position.x > 8)
{
player.position = spawnLoc;
EnemySpawner enemyspawner = enemySpawner.GetComponent<EnemySpawner>();
TransitionScript script = transition.GetComponent<TransitionScript>();
StartCoroutine(fadeInFadeOut());
enemyspawner.nextWave();
}
}
void TakeDamage()
{
}
public void getPlayerPos()
{
playerPosition = player.transform.position;
}
public void nextWave()
{
}
IEnumerator fadeInFadeOut()
{
TransitionScript script = transition.GetComponent<TransitionScript>();
script.fadeIn();
Debug.Log("Faded In");
yield return new WaitForSeconds(1);
script.fadeOut();
Debug.Log("Faded Out");
}
}```
Brilliant, the cause of the error is very obvious and you managed to NOT post the code causing it
I fixed it i see it now whoops
which Input u want?
yo could i use probuilder with blender models?
you can probuilderize the model and then it can be modified w/ probuilder
aight thx
Anybody know How would I wake a TMP text equal an int or float of another script?
do you perhaps mean you wish to set the text property of your TMP_Text object to the value of that int or float? if that is the case, you simply need to get a reference to the object with that value you wish to use on it and assign to the TMP_Text's text property
Hello I am having a problem that produces no error. I am using a navmesh agent, and have set points that an ai needs to go to. once it reches a certain point though it just stops and wont go to the next point unless I move it past a nonexistant line, but it starts moving again if I move around the floors with navmesh surfaces and goes along without a problem until it needs to go back to the second point. Does anyone know how to fix this?
show relevant code as well as the settings on the navmeshagent component
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you have a lot of nested if statements. have you done any actual debugging to find out if the conditions are evaluating to what you expect?
Yes and found absoutly no errors
what did you do to actually debug any of that? because you don't have any useful logs in the code
I did have them than rage quit without saving there was a travelling and arrived debug
that does not sound like useful information that would tell you what your conditions are evaluating to
hello guys ,where i can find good pathway to learn VR?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yes i am totally beginner
okay, so use the unity learn site which the bot conveniently linked after i used that command
This is my code the errer is waveText = waveText.text = enemySpawner.Wave; says I cant convert int to string is there a way I should be doing this
public class waveTextScript : MonoBehaviour
{
public TMP_Text waveText;
public EnemySpawner enemySpawner;
// Start is called before the first frame update
void Start()
{
EnemySpawner enemyspawner = enemySpawner.GetComponent<EnemySpawner>();
}
// Update is called once per frame
void Update()
{
}
void updateWaveCounter(int wave)
{
waveText = waveText.text = enemySpawner.Wave;
}
}```
first off you are using 2 = signs which is a no go
well for starters, that waveText = at the beginning of the line is almost certainly incorrectly.
as for what you are asking about, have you googled it yet?
you have experience or beginner also?
i don't see why that is relevant
i wanna ask a question
bc i dont have your code
Don't Ask To Ask
and if your question is anything about how you can learn to use unity, i will refer you again to the unity learn site
i want to ask advanced question in the field , but anyway thank you
then ask it. did you not bother reading the information in the link i sent about asking questions?
Haven't you said you're a complete beginner? #💻┃code-beginner message
okay i got you, i want to make a big project with my team related to VR in dentistry, and bec we all are totally beginner we dont know how much it will cost , the project for helping dentist students learn the teeth and its layer using vr glass connected to the teeth with sensors
yeah
start by learning what you are doing before worrying about project costs. there's also no single answer to how much a project will end up costing in time, effort, and capital.
thank you and execuse me of what happens
I have set some proper debugs now and it is just saying that the destination is set and it still just not moving
show your current code and what is being printed
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
that nesting is a mess
If you need to know the debugs popping up are the cooldown messages and the set destination
i did specifically ask you to show the logs being printed
but you're also missing some useful information such as whether the agent is stopped and its current position and distance to the destination
How should I write that up
I have a class PlayerMovement with the following code snippet:
private void ResetMovement(bool enteredEditMode, Transform editorArea)
{
[...]
if (enteredEditMode)
{
if (lastEditorArea != null)
{
lastEditorArea = editorArea;
transform.position = lastEditorArea.position;
}
else
{
transform.position = transform.root.position; // <-- Error in this line
}
}
[...]
}
I get the error:
MissingReferenceException: The object of type 'PlayerMovement' has been destroyed but you are still trying to access it.
How does this have to do with the existence of PlayerMovement? Why should it be destroyed at this point? It even sets the position, but still gives me this error.
GameManager.Event_ResetPlayerToLastEditArea += () => ResetMovement(true, lastEditorArea);
This is how I call it btw, Copilot suggested it, is this wrong?
your event is probably static and you never unsubscribe from it. so when the scene is reloaded the new object subscribes to the event and that one probably works fine, but then the event still tries to call invoke the method on the destroyed object afterwards
Oh I did see it work just fine once after recompiling
I only unsubscribe in OnDisable
private void OnDisable()
{
GameManager.Event_ResetPlayerToLastEditArea -= () => ResetMovement(true, lastEditorArea);
}
that is unsubscribing a completely separate lambda expression. each time you create a lambda expression it creates a new instance of it. even if it is identical. You need to store the expression in an Action typed variable in the class, then subscribe and unsubscribe using that variable
or write a method that calls that ResetMovement method and takes no parameters and just (un)subscribe with that
Ah I see, working with expressions you don't understand anything about should be doomed to fail. I'll just sub and give it a method, then call that with those values
Exactly what you just suggested, thanks a lot!
I am trying to create a sprite at runtime that turns an image red.
int imagewidth = (int)TheMap.rectTransform.rect.width;
int imageheight = (int)TheMap.rectTransform.rect.height;
// create a texture with the same dimentions
Texture2D maptexture = new Texture2D(imagewidth, imageheight);
// make a color array of appropriate length
Color[] BackgroundColor = new Color[imagewidth * imageheight];
// fill the array with nothing but red
for (int i = 0; i < BackgroundColor.Length; i++)
{
BackgroundColor[i] = Color.red;
}
// set the texture to use the color array, starting at 0,0 and continuing across the whole image
maptexture.SetPixels(0, 0, maptexture.width, maptexture.height, BackgroundColor);
// set the UI image's sprite to a sprite made from the newly colored map texture
TheMap.sprite = Sprite.Create(maptexture, new Rect(0.0f, 0.0f, maptexture.width, maptexture.height), new Vector2(maptexture.width / 2, maptexture.height / 2));```
However, it appears to simply be making a transparent white sprite instead of the solid red I'm looking for.
!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.
the alpha of the sprite is probably 0
Sorry it took so long I have added a moving debug here is the new version of the script and it is sending the debug not moving
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
oops I'm a dummy, had to send the texture to the GPU
after the setpixels
thanks all!
https://docs.unity3d.com/ScriptReference/Texture2D.Apply.html (for anyone else poking at this in the future)
what's the issue with brackeys or code monkey? as long as you know what you're doing, their tutorials provide some amount of benefit, either introducing you to a new part of the API or showing you a different use of something you already knew
Really really bad habits in their beginner videos.
There are far better resources, so there is no reason to ever warch those ones
Their intermediate/advanced or specific ones are fine
The issue is beginners do not know what they're doing.
oh alr
i thought you meant in general
they were bad
Well honestly, yes a bit. But I prefer to avoid youtube entirely
Their other stuff is FINE, but not great imo.
And written guides are almost always better
written guides are harder to come by though
and docs are extremely hard to parse through for beginners, no?
i feel like if i didn't know how to code, reading through docs (which inherently require SOME knowledge of OOP, given the fact that they reference inheritance trees, methods as members of classes, etc) would just leave me discouraged
No
Hard disagree with all of that.
I learned from docs in every engine I have used. Plus some articles and just researching computer science concepts themselves