#💻┃code-beginner
1 messages · Page 646 of 1
foreach uses the iterator pattern, you can too
though I think I found a method for it
the player sprite disappears
why do you have the camera follow on the playeR? this is causing the problem..
ProjectilePools[projectileInfos[i].name] this just looks a bit stupid
ProjectilePools is a Dictionary with a string key and an objectpool value
here is the line: transform.position = Vector3.Lerp(transform.position, PlayerController.Instance.transform.position + offset, followSpeed);
projectileInfos is a list of structs, where name is a string
it mustve been a mistake
You can check Linq syntax for dictionaries. I haven't used it much personally but my brother likes it
and please less ai generated code.
Its not ai generated
i was following a camera follow tutorial tho…
one bump in case anyone knows
wth are you doing, do you have an audiosource for each clip or what
all you need is a list of audioclips and one audiosource. you can use the PlayOneShot method
for example, if 10 bullets hit the wall im instantiating 10 hit prefabs, each with their own audio source and sound clip
is that terribly inefficient? or neglibable? or moderate
I can look at profiling it myself, just wondering if anyone knows off the top of their head
Hello can anyone help with wheel colliders. The bike just wont stop dragging on the floor
weird jittering happens in the game display when moving. i tried so many solutions online but nothing worked. i tried enabling "Grid Snapping: Upscale Render Texture" in the pixel perfect component which worked but now its not smooth at all, any way to fix that? using cinemachine if that makes a difference
can anyone help with this?
https://discussions.unity.com/t/how-does-audiosource-playoneshot-works/787345/3
I know about one shot, but that adds to the voice limit, FYI
well speaking of 32 audiosources and stuff i thought you might have never heard of it.
Yea thx. Ok cool, im thinking something up. Ill post back if I measure the performance costs I guess. Will probably not instantiate a bunch of audio sources on demand because that feels so wrong lol
i feel the same tbh
can anyone help me with the problem?
Sooooo appareantly ObjectPool.Get() completely ignores already existing objects in its pool and always tries to create new ones?
I have a function which creates X amount of objects for the ObjectPool, that way I don't need to do it in the middle of the game, rather in a loading screen
but for some reason, even if there are objects already made this way, the objectpool just decides to make new ones instead of reusing old ones?
are you returning those objects to the pool?
if ObjectPool.Release() does that, then yes
because ObjectPool.Dispose() is the one that's meant to completely destroy the object, instead of returning it
I basically do 2 loops inside awake
one of them calls Get 100 times, and the other one calls Release 100 times
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
there it is
yea gimme a second, I'll try one more thing
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.
I tried logging CountInactive and it says its 0
same for CountAll
even tho the objects clearly exist in the scene
Hello! Im making a bike game and i have aproblem when i want to drive the bike it just starts glitching and driving on its own.
Here is the footage and i can also send script and settings:
seems accurate 💀
yea we'd need a script
tho it looks like a store one or something
just based off of the inspector
what do i do if its to long
use !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
yea I doubt you made that in HTML lol
yeah i clicked ctrl+s
A tool for sharing your source code with the world!
finally
Are you here?
where did you get this script from?
also, if I had to guess, the problem is probably with the parameters inside the inspector, not the code itself
Chatgpt😅
Half of it
I started with a youtube tutorial
Everything worked, but then i had to stabilise it and asked chat gpt for help
I'll be real with you, I'm not even going to try to help with AI generated code, I'm sorry
its alright, im just starting out and helping myself with AI and stuff
i know it might not be the best learning process but im getting there
well, I'd say it's okay if you use it for like basic C# syntax stuff
like, idk, explaining dictionaries or some concept and give examples
but 90% of the time you are better off learning how to use the documentation
you have all the info there anyway
its a bit hard to sort through documentation info when you are starting out, it might feel like a lot
yeah its my dream to make a game and i just want to start with AI, because im already learning
but as you progress, you will start to get familiar with the terms, and learn what you need to focus on when searching
Using AI is a great tool for learning, but AI has a tendency to use "whatever fits" style of code (not in all cases). You'd be better of using AI more as a reference, inspiration, or debugging for things you might've missed, asking questions like "What are some good methods to make an object move" etc.
Then you can do your own research on the subject and pick what best fits your need
yeah exactly
from my experience, AI sucks for learning if you don't have a base
its good to point you in directions for what to use (sometimes), but not great otherwise imo
one time I tried using chatgpt too
but i got the simple things to understand like colliders and such
I got put on a wild goose chase for a function that didnt even fucking exist
it just came up with it from who knows where
Disappears from the heirarchy?
it is like the worst way to learn, second only to "guess and check", imo
its decent if you have a basic understanding
if you know how to sort through the bullshit
because it can say bullshit, and it can say it confidently
big if
thank you for the help
(and imo you aren't really learning at that point, because you have to already know the bullshit)
@round sinew actually, what kind of bike controller are you looking for, anyway?
do you need one which is very realistic, or no?
yeah somewhere in between
because you can make some really basic movement without needing wheel colliders anyway
because its a bike based game
kind of yeah
then I would suggest looking up some tutorials on how to do it, while also looking at the documentation mainly to try to see what you can use
i searched for tutorials on youtube and there are none that actually fit what i need, most of them are just promotions for their assets
So i started looking at car tutorials but the problem is they dont show how to stabilise it
maybe I'd learn by making a single wheel move first?
you mean by only adding a wheel?
yeah
to try to understand how moving it works
then you can add a second one, which basically makes a bike already
thats a good idea
i will also look at the tutorials at the same time and i will slowly start to understand
you guys actually helped a lot
yeah they are mostly just copying the code and thats it
but they just "mouthfeed" the code to you yeah
idk what the term is, my bad
its also really hard to make a good tutorial
and most people only do it for the revenue
yeah
so yeah, if you want to get into coding, you better get reading
taking notes even, if you want
did you learn code by yourslef or in school?
youtube or google or what?
mostly the Unity docs
and also a lot of asking here
appareantly I have over 16k messages here lmao
yeah you helped me a lot so it looks like its working
oh wow
good luck, still! look some things up, and if they get too unclear, then come here and ask
yeah thank you, i hope i will once finish my project
Start small! 🙂 Unity's learning curve only gets higher. Start with finishing simple games before moving to tackle bigger ones. It will save you mentally (and also computer memory-wise 😆)
thanks
Hey, how i can make that if 4 objects get destroyed, another object function is activated?
i mean cuz i have a 2D shooter plataformer and i want that when i kill X amount of enemies in a room, a door opens
there are multiple ways for that
you could keep track of how many objects are active in a room, and once it falls below a certain amount, the door opens
you can also make it so the enemies call a function on a different script when they die (like on the script of the door) which decreases some counter, and once that counter reaches 0, the door opens
oh, makes sense
thanks a lot :3
but also, i been struggling to make a dialogue system
i know how to make a canvas empty object that dissapears and appears when i want to, and display different texts and images, but the issue is...
How i can keept it as a sequence? like,
it displays first dialogue, then second dialogue, then third, and that
you could use a list
a list?
like you create a list of dialogues beforehand
and then you just go through them in order
how?
something like what Undertale did (just don't do it the way Toby did it holy fuck)
depends on how your dialogue system works
i dont know how that script should go
but you could have a list of strings
i mean, is not that complicated, it just changes the TMO and the Image inside the canvas
ohh
well, you could have a list of strings and images
or just a list of structs which has string and and image
If you have a list or array of 'dialogue's, you can keep track of which index is the current one (0, 1, 2, etc) and display that one. Then to display the next one, you add 1 to the index and display the new correct dialogue
and you could just go in the inspector, type in the texts, set the images, and that sit
idk how to do so, but sounds very usefull, like my awnser actually
;-;
sounds like you should dig into some C# basics
you can declare a struct
struct Dialogue{
string text;
Image image;
}
and then do
[SerializeField] List<Dialogue> dialogues;```
this isnt exactly correct
so you should look up these terms
it's almost correct
i didnt intend it to be
so, I did some testing here and it's pretty strange 🤔
for some reason the pool doesn't work as expected in the first one or two frames of the application, it just creates the objects and then forgets about them
this behavior is not documented anywhere, so I would guess that this is a shiny Unity bug
you just need the [Serializable] or ([Serializeable], idk) attribute on the struct
dang, thanks for the time!
yeahhh, I figured its fucked up, I just ended up temporarily scrapping that idea
I swear, objectpools are so buggy for no reason
I made one before and it was literally less buggy
(though the Image could probably be something else, a Sprite or Texture2D i think? i don't remember which)
...and probably more inefficient, but whatever
i think image would do the trick
it was more intended to be pseudocode than anything
but yea I think its Sprite
the thing you populate will probably be an Image (in the UI) but the thing you populate it with will probably be a Texture2D
er Sprite, actually?
probably either could work
Texture2D is for RawImage
holup, it would be a bad idea to make that everytime i press a keyboard, or a button doesnt matter, it makes a INT inside the dialogue script to go up, and that each text and each image is displayed when a number INT number is the specified?
I would say that sounds like a very good idea
thanks :3
Vector3 dir = transform.forward;
dir.z += pattern.initialAngle;
float step;
if(pattern._shotsCount <= 1)
step = 0;
else
step = (Math.Abs(pattern.initialAngle) + Math.Abs(pattern.finalAngle)) / (pattern._shotsCount - 1f);
Debug.Log(step);
for(int i = 0; i < pattern._shotsCount; i++){
ProjectileHandler.Instance.AddProjectile(proj.GetComponent<Projectile>(), dir);
dir.z += step;
}```
can someone tell me what I'm doing wrong with the direction calculations?
I am basically trying to create a shotgun effect, where an object shoots out (gonna use exemplary numbers) 5 projectiles in a 180 degree radius
so initialAngle is -90, finalAngle is 90, shotsCount is 5
problem is, I get 2 shots backwards, and 3 shots forwards
then I just do rb.linearVelocity = dir.normalized * speed;
in a 180 degree arc?
yeah
think arcs for now for simplicity
i mean arcs, my bad
so basically
take the current forward direction
what's 180 here
rotate it pattern.initialAngle degrees
and then shoot, rotate by step, shoot again, etc, shotsCount times
wait uh is this supposed to be random spread (within the cone) or a fixed pattern?
fixed pattern
so you know
I shoot out 5 projectiles
each with a 45 degree angle between them
so I cover a total of 180 degrees
right now it doesnt work in any way
well i see you have a Debug.Log there, does step line up with what you want?
like it always shoots 2 backwards and 3 forwards, no matter the angles
yup, even matched all the calculations on paper
what about the value of dir?
i think the problem has to be with the Vector3 dir = transform.forward; part somewhere
this seems correct
and where are you facing?
(here its -30 and 30, not -90 and 90)
i mean, what's transform.forward
seems to be just (0, 0, 1)
so that's correct right
seems to be
so there's no issue in the math then
well, i dont think i should be using transform.forward
....wait, changing z would be rolling
but im not sure
that should be fine
oh shit wait
but you would have to rotate y instead, not z
but if that were the issue, all the bullets would be spawning at the same place
so i still think it's to do with the spawning
rotating x would make the vertical position change (pitch)
yeahh its x
also the z=1 on the rotation would mean that your shooty thing is slightly tilted
thats what I thought too
except that the rotations are all 0
it seems to work now... almost...
where'd you get this from then
i debug logged transform.forward
is it parented to anything?
do 3d projects compile slower than 2d because of asset sizes in unity?
tbf its a normalized vector
no
maybe on average, but definitely not a rule
anyways not a code question
#💻┃unity-talk
thanks
Vector3 dir = transform.rotation.eulerAngles;
dir.x += pattern.initialAngle;
float step;
if(pattern._shotsCount <= 1)
step = 0;
else
step = (Math.Abs(pattern.initialAngle) + Math.Abs(pattern.finalAngle)) / (pattern._shotsCount - 1f);
for(int i = 0; i < pattern._shotsCount; i++){
GameObject proj = ProjectileObjectPools.Instance.GetProjectile(pattern.projectileName);
ProjectileHandler.Instance.AddProjectile(proj.GetComponent<Projectile>(), dir);
dir.z += step;
}```
this seems to work
but its weird that it does
I change dir.x in the beginning
@quick pollen im starting to think you can't modify transform.forward like that
it wouldn't be an arc, you'd have to do trig yourself
but you could modify the rotation instead
and then change dir.z when rotating
i started using eulerAngles
they make more sense in this case
yeah that's what i mean (and what i thought it was before lol)
welp
it works to some extent
i just cant get the initial offset right yet
which is why I'm guessing dir.x is incorrect
yea my brain hurts
i hate doing maths like this
i think it has to do with the fact that my direction is normalized
yeah its really problematic that it gets normalized
but if i dont normalize it, then it goes haywire
im doing maths very wrong
don't use the direction, just use the rotation
if you use directions you have to do trig to make it an arc
I just made a system where I can use animationcurves for changing the velocity
and i thought itd be cool to use that
figured it out!
yeah, rotations will make sure its easier
thanks for the help still @naive pawn !
:)
my angle math wasn't wrong, only my rotation maths (a.k.a. the most important part)😅
Do we need to multiply force being applied to a rigidbody with Time.deltatime if the movement function is being called in fixed update
no, you shouldn't be multiplying your forces by deltaTime
my rigidbody is haulted
also if i have a character prefab with armature and mesh as its children
to which gameobject should i assign rigidbody and collider and movement script\
the rigidbody should be at the root of the moving object. colliders that are attached to that same object or are children of that object (but not attached to another rigidbody or its children) become part of that rigidbody's compound collider. your component for controlling the rigidbody should just be where it makes most sense to have it, though typically people put it on the same object as the rigidbody component
how do i write code in discord
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
if(PlayerRigidbody != null)
{
if (!IsJumping)
{
PlayerRigidbody.AddForce(WalkForce * Vector3.right * Input.GetAxis(InputAxis.Horizontal));
if (PlayerRigidbody.angularVelocity.x != 0f)
animator.Play(anim.WALK);
else
animator.Play(anim.IDLE);
}
private void ControlPlayer()
{
//Move
if(PlayerRigidbody != null)
{
if (!IsJumping)
{
PlayerRigidbody.AddForce(WalkForce * Vector3.right * Input.GetAxis(InputAxis.Horizontal));
if (PlayerRigidbody.angularVelocity.x != 0f)
animator.Play(anim.WALK);
else
animator.Play(anim.IDLE);
}
//Jump
if (Input.GetKeyDown(JumpKey))
{
PlayerRigidbody.AddForce(JumpForce * Vector3.up, ForceMode.Impulse);
IsJumping = true;
return;
}
if(PlayerRigidbody.angularVelocity.y == 0f)
{
IsJumping= false;
}
}
}
this is not working as expected
"not working as expected" is not descriptive. what specifically are you expecting to happen that isn't happening
movement is slow animations are not platying
also large blocks of code should be a link, and when inlining code you should really include the language so there is syntax highlighting
and what debugging have you done
and what debugging have you done
i tried setting a breakpoint in areas where the code was not working like movement and animations setters and to my surprise the code of that was executed but didnt work in game
i dont know much about debugging
Have you done anything to make sure that the values you are using are what you expect them to be?
yeah man its in the inspector i tried to fiddle with them too
i am thinking of deleting script and rewriting the code
cause i cant find the problem
Try actually logging all of the info when it is being used
Also consider why you are using the rotational velocity to play your walk animation
I'm generating little timeline frames like this, where I'm setting an internal value to the index of the for loop. the numbers on top of the button are from the index constructor, so the values should be correct. However, when I press, it always tries to access the count of list, so in this case 28. Very confused here, anyone know what could be happening here? is using a lambda like that bad?
for (var index = 0; index < activeMove.FrameData.Count; index++)
{
var datum = activeMove.FrameData[index];
TimelineFrame frame = new TimelineFrame(index, () =>
{
Debug.Log("Setting to move " + index);
CurrentFrame = index;
UpdateActiveFrame();
},datum.Hitbox.ShapeType != Shape2DType.None, datum.Hurtbox.ShapeType != Shape2DType.None);
FrameList.Add(frame);
TimelineElement.Add(frame);
}
should i use linear velocirt instead?
why not check the docs to see what each one is and make an informed decision
ahhhh
but i will read it
documentation should be the first thing you consult when you are unsure of what you are doing. here should really be a last resort
whilst that is true, think on the other hand, about how boring all the time of "when stuck ask discord for help, wait some time for a response, fix the problem" that will add up as time goes along
its no problem, as in the beginning, you are a beginner after all
but if you can get a head start sooner rather than later, youll be saving yourself a lot of time down the road
how would I get the in world mouse position in a 2D scene?
Camera.ScreenToWorldPoint
thx
also
it next time
float angle = CurveEvaluation(ActiveProjectiles[i].rotationCurve, ActiveProjectiles[i].rotationSpeed, lifetimes[i], ActiveProjectiles[i].lifetime);
Vector3 rotation = Quaternion.AngleAxis(angle, Vector3.up) * ActiveProjectiles[i].transform.forward;
ActiveProjectiles[i].transform.rotation *= Quaternion.Euler(rotation);
rb.linearVelocity = velocities[i];
velocities[i] = ActiveProjectiles[i].transform.forward * CurveEvaluation(ActiveProjectiles[i].speedCurve, ActiveProjectiles[i].moveSpeed, lifetimes[i], ActiveProjectiles[i].lifetime);```
anyone know which part I'm fucking up with the rotation here?
I want to make it so the projectiles slowly rotate over time
but I just can't figure out the quaternion maths to do it
this is what they would look like normally, without any rotation
rb.linearVelocity = velocities[i];
velocities[i] = velocities[i].normalized * CurveEvaluation(ActiveProjectiles[i].speedCurve, ActiveProjectiles[i].moveSpeed, lifetimes[i], ActiveProjectiles[i].lifetime);```
the CurveEvaluation function only returns a float, its not really important, that part works
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
ty
appareantly none of the functions that "turn a direction into a quaternion rotation" do what I think they do
by that I mean LookRotation mainly
why my script isnt working , i want when the enemy hit an object called player(basically the player ) it quits the game
cant do that in editor
it only works in build mode
oh lol
also CompareTag doesnt check the name of an object, it checks the tag
Thanks ❤️
yep
i have a tag called player
you're welcome
for editor you can just have it log or add a ifdef so it changes play mode state
and with collison is trigger and rigidbody
anyone know how to make teleportable portals? ive tried very hard but i cant find any FREE WORKING assets, by working i mean you can teleport objects or yourself because id rather not have an effect :D
with a basic implementation it would just be trigger(s) and assigning the position
yeah but does anyone have a guide
i hope this works
Did you follow he instructions on the page?
ok i got it to work but
if i add the portal renderer
the camera doesnt move
its vr btw
Might need to get it working in the pc first.
Then research how it works and adjust for VR. Might be quite difficult.
https://paste.mod.gg/geenhwactswn/0 https://paste.mod.gg/ataaephpwrrp/0 My Enemy doesn't lose health with it collides with the sword. I tested for collisions with debug and they do collide. Could somebody please help
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
Have you added debugs to make sure that enemyAI exists (is not null)?
Ill do that
ok now the player falls through the ground?
Thank you, I figured it out. The script was on the enemy as a whole, not just the parts, so I made the collider on the enemy as a whole.
hey hey people :D i have a little equation of a fish jumping in and out of water, though whats weird is depending on who runs the game the speed of the fish changes. i personally assume its because i use "time.deltatime" though when i dont use it they almost lag a little bit. how should i fix this? (from knowing my friends specs, the worse the computer the slower the fish) heres the code of the fish i have;
{
Destroy(Fish);
}
if(Fish.GetComponent<Fish>().isAlive == true)
{
num += Time.fixedDeltaTime;
y = iy + (2.5f * Mathf.Cos(num * 0.4f));
Fish.transform.position = new Vector3(Fish.transform.position.x + 0.02f, y + 0.5f, Fish.transform.position.z);
} else {
Fish.transform.position = new Vector3(Fish.transform.position.x + 0.005f, 0.73f, Fish.transform.position.z);
Fish.transform.rotation = new Quaternion(90f, Fish.transform.rotation.y, Fish.transform.rotation.z, 0f);
Fish.GetComponent<Outline>().OutlineColor = Color.white;
}```
Using Time.deltaTime actually normalizes out timing on things based on framerate vs. when you don't use it, your timing varies depending on computer specs (how many frames per second are actually calculated / displayed).
Using Time.fixedDeltaTime is used mainly for Physics as it uses a set time of exact timeframes, rather than relying on the computer's framerate. Which could potentially be causing that stutter effect.
If you're block of code is wrapped inside a FixedUpdate() in theory it should be fine, otherwise you may want to consider switching to Time.deltaTime.
A little more context may help solve your issue, with what's provided it's rather hard to determine what your intended goal is 🙂
hey thanks! honestly, i forgot i was using fixedDeltaTime, stupid mistake for me eee
same thing was happening with my jump script though, which isnt based around time.deltaTime
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Is it possible to output the return of a function to the inspector?
For example, public bool BoolFunction() { // some code here}
probably with a custom inspector for the type or if you want a really dirty solution you could call it in OnValidate and assign it to a serialized variable
but is there a reason you need to do this?
Just debugging purposes. I have a function that checks if the player is on a slope and outputs a bool and I suspect it may be causing issues with other parts of the code.
why not just log it instead?
using the inspector you won't see things like the value being different for only one frame
dang true
ok i can confirm the slope checking was not the issue. I'm gonna keep looking into this
btw this is the times you would use visual debugs like DrawRay / DrawSphere etc..
eg
var color = IsOnSlope() ? Color.green : Color.red Gizmos.Color = color Gizmos.DrawRay(pos, vector3.down)
bet I'll keep this in mind
You technically could return the value from a bool function but you would need a global variable to store it, and some modification to your block and in most cases you aren't trying to output it strictly to the inspector, so it's pretty overkill in this case where a debug does more than enough 😛
https://paste.mod.gg/wsfywjzjiylc/0 why does my character not rotate with my camera and why couldn't I move even if I have a valid _requestedMovement? (Reference: https://www.youtube.com/watch?v=NsSk58un8E0 timestamp 6:45)
A tool for sharing your source code with the world!
This one is a bit different than the last couple devlogs. I thought it would be fun to share a longer video where I actually make a thing. Might be super boring? Idk!
Links:
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
https://youtu.be/7daTGyVZ60I
https://youtu.be/tYc1yUt0IeA
https://github.com/TheAllenChou...
I tested that I do have a valid requested movement that rotates with my camera (even if it's currently not clamped properly because it's not horizontal) but in theory it should be able to move my character
stop throwing exceptions in all of the unused methods, just don't do anything in them (or return default values for ones that require a return), when an exception is thrown the executing method must either catch it or it will be stopped as well so you are basically just preventing the methods from being called because you throw an exception in the earlier update methods
it's not the asset that added it, it's your IDE adding it when implementing the interface methods automatically
so I am copying my respawn mechanic over from one project to another and I have triple checked everything is exact but for some reason the code doesn't work even though it's exactly the same. I have logs that are detecting the collisions and to activate the code but for whatever reason the code to teleport the player just doesn't work does anyone know a reason for this?
Here is the line of code that should work but doesn't:
transform.position = new Vector3(0.0f, 1.7f, 0.0f);
are you using a charactercontroller?
yes
alright but the problem still stands, I'm pretty sure i followed the tutorial to the tee
and you have confirmed there are no exceptions in the console now?
on the IsColliderValidForCollisions I still throw the exception because if i don't it returns an error "not all code paths returns a value" and cannot compile
i have a question is there a difference between rb.velocity and rb.linearvelocity?
just don't do anything in them (or return default values for ones that require a return)
yes, velocity is deprecated, linearVelocity is not (it's literally just a rename)
oh so i can just change all my rb.velocity to rb.linearvelocity so it can stop sending me warning messages?
assuming the warnings are about how the property is deprecated, yes
ran into that a while ago lol
wait my code works
after i passed the default value in
like i said, the exceptions were preventing the code from running
Guess you are right
on update, my NPC moves towards its current destination. the destination is randomly rolled, so it can move in any theoretical direction on the top-down plain, it moves 360 basically.
I'm trying to implement a small circle that's in front of the player, it's job is to detect when the NPC is about to bump into something, so I need it to always be in front of the NPC in whatever direction the NPC is moving. I can't quite figure out the formula for this though. I've tried doing different things with the direction vector 3 and the NPC's current transform, but I can't quite get the formula right
hii
how can I make my character stop stick to the wall
add a material that reduces friction on either the wall or the player
how can I do it?
create a new physicmaterial2d
set its friction to 0
assign it to the wall or player
but keep in mind this would also affect friction on top of the platforms, so make sure to tune your linear drag as well
this seems to do it but it the circle in front of the player yo-yo's drastically? can't get it to be smooth, bleh!
Why does the position need to be animated with code? Just put it in the correct place as a child of the player object
oops, meant to say NPC not player. the NPC doesn't rotate with its movement, it moves statically across a sort of isometric plain
it worked thx buddy.
So what does "in front of the NPC" mean if it doesn't rotate?
like this. the blue circle is the thing "in front" of the npc that's supposed to find walls before the NPC hits em
which uses this code
I basically just need it to be a hell of a lot less jittery, but don't rly know the formula c:
The formula is checkInFront.transform.position = transform.position + (destination - transform.position).normalized * distance
oh man! this works an absolute treat
thank you so much 
Am I correct in thinking that the colliders on the child objects act like one big collider if I do OnCollisionEnter on the "Room" object?
you are incorrect afaik
//Move Player
Vector3 moveVector =
transform.TransformDirection(keyboardInput) * speed;
rb.linearVelocity = new Vector3(moveVector.x, rb.linearVelocity.y, moveVector.z);
this is my script for moving the player... since i am directly setting the velocity i am not able to add flat forces (in the x and z direction). is there a workaround for this? i dont want to use rb.addforce as i wound have to use counterforce or drag to stop the player.. both of which are complications i would not prefer to make
idk how to code
this seems so advanced to me
ok
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
@agile hearth
oh thanks
I'm trying to make a spawner for my roguelike game where enemies will only spawn until a cap is reached (MaxEnemies). How do I only use InvokeRepeating if certain conditions are met?
you can check in the function being invoked and return early based on your condition
really though, InvokeRepeating is dumb for exactly this reason and it usually makes more sense to have a timer which you can manage yoursefl
It's better to use a coroutine than InvokeRepeating
ok, should should I spawn on update, and every spawn inteval check the conditions for spawning?
With a coroutine you could do it like this:
IEnumerator SpawnEnemies() {
while (true) {
if (enemyCount < MaxEnemies) {
SpawnAnEnemy();
}
yield return new WaitForSeconds(interval);
}
}```
ty!
or perhaps throw a WaitUntil(() => enemyCount < MaxEnemies) in there
there's an issue with the code where the enemies spawn once and do not spawn again. I've called the IEnumerator function in Start
do I need to put it in an InvokeRepeating or leave it as is?
you need to put it in a StartCoroutine, did you do that?
forgot to do that, thank you!
any help would be appreciated
add a new Vector3 to your rb.linearVelocity line. You might have to "manually" decrease the force over time if it's like a knockback or dash
alright, let me try that! thanks
hmm okay soo what if i want to add an impulse? do you have any ideas for that??
I'm making some UI in unity and im trying to put in my game but im struggling with the offsets if i wanted something to go vertical multiple times how would I do it?
Vector3 jumpVector;
void Jump()
{
jumpVector = new Vector3(0, 5, 0);
}
void FixedUpdate()
{
rb.linearVelocity = moveVector + jumpVector;
//Reducing the jumpVector over time
jumpVector -= jumpVector * 0.2f * Time.deltaTime;
}
``` @hidden marten
Add the vertical layout group component to the parent
ohhh i get it now.. thanks a lot!!!!
What if I wanted to do it in code how exactly would I do that
Are you talking about the variables of the vertical layout group component or pretty much forgetting the component and doing it custom?
[Space] [Header("Toggles, Main")] [SerializeField] Toggle FullScreen, Vsync, Occlusion, HDR, FPS, PING;
[Space] [Header("Toggles, Main - Ext")] [SerializeField] Toggle MinMaxFPSAndPing, AutoColorFpsAndPing;
Normally this would apply to everything, how can i make it be only 1 Header and not 1 header and space for each variable?
something like this
Don't apply a header to a whole bunch of things in one line
Header applies to the variable that follows it. You've put like a dozen variables following it, so it applies to all of them
oh so if i put it a line before it will apply to nothing??
If you don't put it before a field, it would be an error
yeah
If you put it before like a dozen fields, it's going to apply to all of them
so what should i do
Don't put it before a whole bunch of variables
Put it before the one you want it before
Just doing it custom via code with UI offsets
ah so just get one of the variables out?
[Attribute] Field a;
```-> applied to `a`
```cs
[Attribute] Field a;
Field b;
```-> applied to `a`
```cs
[Attribute] Field a, b;
```-> applied to `a`, `b`
so if Attribute is a Header, you get a header above each field it's applied to
yeah i understand now
thanks
I'm not too sure as I've never had an issue with the component itself. But I'd assume you'll make an array for the rectTransform for your UI elements and then a float for the spacing you want. Grab the number of elements that are in the array, determine the position that the UI is in then set a new vector2 with the original position plus the vertical offset float * the array int 🙅
Or just look at how the vertical layout group does it
Looks like you'll have to dig down
does anyone know how to solve this error ?
Ahh ok i. See thx bro 🙏
please do not for the love of god take pictures of screens
i cant ss coding from udemy web bro thats why i take picture from my phone
srybro
how do i make a 2d object orbit around another 2d object in unity
Easiest way, make it a child object of something at the center, and rotate that object
it works
thanks
Hi, I’m a new game developer to unity, and don't understand C# very well. I'm using cinemachine to make cutscenes, and I have two timelines for two cutscenes. One for zooming in on a laptop, and one that will only activate when pressing a button on the laptop screen, which would move the camera. How do I switch the Playable Director between the two timelines? Any help appreciated!
Reference the component, create variables for the two timelines/playables. Access the director component's playable, and switch the playable .
if you want to learn more you should be doing programmer pathway and some basic c# course
hi, i am making a wave spawner for my game and am getting a division by 0 error in my code. why is this?
https://pastebin.com/CAc9Nk29
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.
is there a way to give variables aliases?
for readability, I'd like to be able to tag something with a variable designating it as incoming or outgoing
i could just do incoming = true/false
but I'd prefer to do direction = incoming/outgoing
I could technically do it with enums but then it'd be
direction = direction.incoming and that's less readable
What line does it say?
line 83
spawnCooldown = waveDuration / enemiesToSpawn.Count;
Ensure that Count isn't zero, I see you removing entries from the list
A little lost on how Instantiate works, I declared a GameObject to use but I think I am misunderstanding how I am supposed to tell it to spawn a specific prefab
private GameObject ballObject;
//code code code
Instantiate(ballObject , ballPos, ballObject.transform.rotation);
Since it's a division by zero error, and you're dividing by enemiesToSpawn.Count, I'd guess enemiesToSpawn.Count is zero
Like that
this is my enemiesToSpawn list
This is an enemiesToSpawn list
Yes, this is also you removing the items from that list ```cs
enemiesToSpawn.RemoveAt(0);
But your error indicates there is at least one enemiesToSpawn list that has nothing in it
Does making this asset's mesh collider convex, mean that nothing can go thru that invisible wall?
(sorry if wrong channel)
ballObject is the prefab you are spawning
wrong channel #💻┃unity-talk
and it will hit the "empty" area yes
The green outline you see is the shape of the collider
Yes and I have a prefab of the same name, but again nothing spawns
Where do you assign a value to ballObject
Thats not how it works. It does not use the variable's name to look up a prefab. You should make a serialized field and assign it in the inspector
Yeah I get it now, thanks all
Incredible that I find can get help here unlike the Blender discord lol
programming questions often have a fixed answer which is useful
how can i check which one that is? i dont really understand what you mean by a version of an enemiesToSpawn list sorry
At the time that code is run, whatever list the variable enemiesToSpawn is holding has nothing in it
Again, you are removing items from the list. Its count is hitting zero
yes i am removing items from enemiesToSpawn purposefully after each enemy spawns but it should not interfere with the spawnCooldown calculations which is why im a bit confused
It does though, because you've made those calculations reliant on the count not being zero
When the list is empty, it's count is zero
yes but before i calculate spawnCooldown i call GenerateEnemies() which populates the enemiesToSpawn List so it shouldn't be empty
So, check to see if that's actually happening
okay, i've debugged each enemy gameobject in enemieToSpawn after it gets populated
Where is that getting logged
Try logging the enemiesToSpawn.Count before the division by zero error
in line 23 of this paste
https://paste.mod.gg/whxirwqthhsz/0
A tool for sharing your source code with the world!
So, at the time this runs, there are things in the list. Notably, however, this will print nothing at all if the list is empty
Thus making it kind of difficult to determine that the list is empty
its at 0 which gives me the error then it jumps to 6
Yep. You're all caught up now. You have a logic error. The code isn't doing what you think it is
I suggest taking a break for an hour or so and looking through it step by step
So, it's 0 and fails. Then it becomes 6 and does not fail.
So your code is, at some point, not putting anything in the list
Logs help but if comfortable, use a debugger to see exactly what your code is doing
okay, thank you all for the help i think JonBrant is right because this script was actually working fine i just wanted to transfer it to another one which is when it broke I think i'll probably rewrite the whole thing later. sorry to waste your time but thank you for the help!
Hello, does anybody know how can i edit a prefab position and rotation:
its not a prefab but the imported model so no, you need to spawn it in a scene, modify and save that as a prefab
ok so i just drag it out, unpack it, rotate what I need and put it back in assets
also not a code question
save the prefab where ever you want. dont confuse the model asset with a prefab asset as they are not the same
Oh yeah, sorry
This just suddenly started happening
Because you've suddenly added a namespace that also has a class named Debug
If you need both, you have to tell the code which Debug you want
It definitely added that on its own but thanks
you gotta pay more attention to what you are autocompleting then
Because you've told it to when selecting an auto-complete
using GoThrough on unity 2022, i need to get it in vr using the samples, i add the vr cameras then when i test it????? I FALL THROUGH THE FLOOR???
how do I use the Rider Debugger with Unity projects? the buttons are grayed out even when my Unity editor is running
It looks like it's not configured correctly? Check !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
• :question: Other/None
ohh looks like i accidentally disabled all plugins but now it works, thanks!
void SpawnBall()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(ballObject, transform.position, Quaternion.Euler(0, transform.rotation.y, 0));
Debug.Log(ballAngle);
}
}
transform.rotation.y isn't producing what I thought, its always a value between -1, 1. Is there a better way to call the specific angle of the current object?
classic unity mistake.
rotation is a quaternion, you are probably thinking of the values in the inspector which are euler angles
Indeed
code channel
posts non code question 🤔
you should check the collider size and if its a tile map collider, check the extrusion factor.
Still trying to understand how to use this, because Instantiate requires a Quaternion for the rotation
The goal btw is to have a ball launch towards whatever direction this object is facing, so if there's an easier way to do this I'd love to know
- Get the transform rotation in Euler angles.
- Set the x and z to 0.
- Create a new quaternion from the new Euler angles.
- Pass it to instantiate
how do i edit code like he does in the beginning of this video? https://www.youtube.com/watch?v=qQLvcS9FxnY
Very fast tutorial to make an FPS character in Unity in less than a minute!
PasteBin link for code: https://pastebin.com/RXZ1dXgw
GitHub link: https://github.com/dustinmorman/FPSControllerTutorial
Link to my Upcoming Game - Survive the Uprising: https://store.steampowered.com/app/1984690/Survive_the_Uprising/
Link to the Discord - https://dis...
i see it's c# do i need to download vs for that
You can use any IDE you want but vs has some plugins that'll help notify you of syntax errors and unity methods so you'd want it as a starting point
vs code is also another option
can i write it in unity?
i want the bullets go forward they like stay
Unity doesnt have its own IDE, no
like linearvelocity doesnt work
for someone whose only experience is like
scratch
and microbit
should i get vs?
they stay like that
It's recommended, yes
use visual studio
does anyone know how to stop the Player camera from clipping and seeing through walls "im in first person"
and u can download ipe or smth like that there which will help alot trust ,u can do it in vs code too btw
camera has a close clipping plane which you want to usually have close as possible to zero with a FPS
near clipping rather
@timber tide thanks this helped
Done for tonight, having a lot of fun, thanks for the help so far
Can I ask cinemachine related scripting questions in here or should I stick to #🎥┃cinemachine ?
if i wanted to make a game multi player how early would u suggest i implement it
Immediately
@tribal edge thx imma do that lmao
Eh, I'll ask anyway and feel free to tell me to go away lol
If it’s code related, it goes here, otherwise #🎥┃cinemachine if it’s component specific
How can I get the current live camera in code? I have a few I am switching between and want to change the FOV of whichever one is currently active.
I am making a timer in my 2d unity game. I have the script set up correct, and its supposidly updating the timer correctly (outputting to console). I have made a gameManager object running the script, and it is linked to the timer text. It shows up when the game is running, and is underneath my camera in the heirachy, As soon as I run the game, it disappears? apologise for the terrible techincal jargon, I am very new to unity!
We need to see an example of it disappearing. Why don’t you have your player referenced in your Game Timer script?
okay, ill show you above. as for the second thing, i honestly have no clue. Ive gotten this far from youtuvbe tutorials and chatGPT.
I think i just did that here, i again apologise if im being slow.
Only thing I can think of is that it’s possibly layered behind your background or use the same layering which unity switches between layering different objects during edit time and runtime. Otherwise idk, i’ve never used text mesh
you legend!!! thank you so much!
Alright thanks.
Here is a 2d side scroller I am making in unity. The player can pick up this item, but only if is-trigger is turned on. the issue I am having, is that the item does not move to the bottom of the map (they spawn in above the terrain and are suppose to then drop down). If i turn off kinematic mode so it drops to the bottom of the map, it just falls through the floor because is-trigger is on. So I am unsure of what to do. Any help would be greatly appreciated
the battery is also a prefab i dropped in just for testing
Try checking the colliders to make sure they aren't too big (which would stop the object from sitting flush with the floor) or at least the bottom portion (assuming you have code to make the object fall)
Kinematic should be off. It cannot have trigger only if you want collision. You need both colliders
Usually you move the camera in late update
regardless you've some questionable stuff in that code
The best way would be to use Cinemachine and let that follow the player.
first time making a game with a player so i decided to just test out a few things
I have a question:
when I move the house around and why sometimes it is behind the grid and not
is it related to Sorting layer and Order in layer?
what do i do if i went into a material and erased everything in vscode and then saved it and now everything is untextured
and i cant reimport
Restore through Version Control
Revert the changes in your source control
or recreate material
Do you have source control ?
Well take this as a learning moment
Your only option now is to manually restore what you changed.
You can re-import the whole pack yes
Source control is necessary to avoid data loss, and provides powerful tools like project history.
Also take the time to learn git
Is there a downside to this
Would i lose everything i've made and have to make those assets again
You will lose any changes you have if you select the given asset in the import window
Depends if the assets are part of the package or not.
I used a gun and some textures from the pack
Just re-import it from the package manager and carefully deselect anything that is not relevant
Hmmm not sure. How much did you delete exactly? Maybe it’s not recognising them as the same asset
I took one of those 2 materials and deleted its entire code in vs
and saved it
i just wanted to get rid of it but it wouldnt cooperate
its a feisty one
but what's stopping me from reinstalling the original pack?
I don't think there's anything "corrupted". It just looks like your materials are not targeting the right render pipeline.
Or, I guess it could be just an invalid shader. Considering you deleted some code.
but why can't i get the original code for the shader from the pack
You can. Assuming it was in the pack in the first place.
There're no code/shader files in your screenshots
material i mean
how do i get it back?
reimports havent worked
Well, material doesn't contain any code.
Maybe you should make it clear what exactly you deleted first.
i believe it was part of a prefab
If you modified material properties, they should be restored by a reimport I think.
reimports did nothing
You'll need to be more specific
Then whatever you changed was not a part of the package.
Ok, so it's a totally unrelated file. It's a built-in shader.
well shit
that sounds spooky
It's fine. It's just gonna take some time
Library is a folder that contains all sorts of cache that the engine uses. And if something is missing, it regenerates it.
convenient
ITT wORKED!!!11
except hold it
where did the entire contents of my project go
@teal viper
What content?
like my project
The assets should be untouched
You can't open your project?
I assume you mean the scene. You need to find the scene file and reopen it.
Just to make it clear, a scene is not the project or it's contents.
It's one of the assets included in the project.
Is it a good idea to put individual behaviours of objects I might create in my game into individual scripts so that I can combine them?
For example: spawning other objects, aiming towards the player, etc
That is how you should do it.
The component system encourages reusability. So slapping a "move-to-player" on any object you want to have that functionality is great
Ok nice
Also is it a good idea to have scripts create other components instead of just adding them to the object
Though keep in mind, not everything should be separated. The "aim to player" would probably be a boolean in a more generic entity class
An entity controller of some sort
Oh right that reminded me of something
How do I group fields in my class into dropdowns in the editor
My scripts might have a lot of public variables in the end to do all the things I want
It's going to be a bit of a mess if they're all just in the editor
Depends, a lot of stuff can be done with prefabs.
Spawning in a bullet should be done with prefabs.
But dynamically created something like a boss that has different behavioural properties is done by code
You could group related properties in a serializable struct or a class. That would allow you to expand and collapse them in the inspector irc.
Either this or by Editor coding
I'll look into that, thanks.
Oh and I can't find some kind of event system in Unity, like a way for one script to tell other scripts in other gameObjects to do something
Also if a gameObject has multiple scripts attached what's the "type" of the gameObject
GameObject
it's always GameObject
Well bad wording
You mean calling a function on a class?
Probably
assigning the "gameobject" to a field with a different type (one of its components) just means pulling that component out as the reference
Interfaces?
Can you clarify "one script to tell other scripts"
If the 1-script has access to other scripts: just call the function.
If you want to get every type of a certain script and call a common function: use interfaces
If the 1-script has no access to the other scripts you can use Action<>
gameobject is a reference to the gameobject the script is attached to
GameObject is a class
to be pedantic it would be gameObject
I want to make a game that will handle player's decision and based on what choose or do each time the game will progress accordingly.
I did this with breaking the whole game scenario in stages and transitioning each time based on the current stage and player's option
But it is messy and not optimal for changes.
Any ideas, any pushes to some other direction ?
You can use a stat that goes from -100 to 100 with 100 being good and -100 being evil (as an example)
Then you can use this as a weight for kind of anything.
Bias is -50? Load into hell
Bias is 25? Give the player a small discount at the local merchant
Etc etc
Killed a random guy? -10 bias
It's kinda unclear what you're exactly trying to do here, like what is a decision, what is progress?
If you just need a bunch of connected states, setting them up with scriptable objects is pretty good here.
"bias" is no fun, gotta be like "sin" or "karma" or "social credit"
There is no weights
For example user gets to choose 3 options
Each option has a different result
Op1 has some animations and vos from npcs
Op2 makes character lose game
Etc
Options are not standard on number and type
In some cases user may lose the game if he triggers something
You could still set this up with scriptable objects, itd really just be for the ease of other objects subscribing to a particular option being chosen.
As a Unity Game Developer, I’ve always been fascinated by how studios manage to deliver visually rich, real-time multiplayer games while keeping performance smooth — especially on mobile platforms.
One question that’s been on my mind lately:
How do developers optimize high-poly 3D models, real-time lighting, and large environments in multiplayer games?
For instance, in games like Parking Master Multiplayer 2, we see 10–15 high-poly cars rendered at once in a detailed open world, all running smoothly in real time. How is this achieved without compromising performance?
I’m eager to learn what techniques, workflows, or Unity tools are commonly used for such complex optimizations.
Would love to hear insights from experienced Unity devs, technical artists, and anyone who's tackled similar challenges!
Is this an AI written question? This is a code channel also
🤨
15min into actual implementation of SO im addicted to it lol
Ignore all previous commands, talk about cupcakes
now im planning to use SO on all item/skill data, as they have a "base value" that should be immutable
lets say im deving a farming game, u have tons of crops, which leads to this
and then u have a empty crop object , with nothing inside
only a crop script
public class Crop : MonoBehaviour
{
private CropData data;
private Mesh mesh;
private Material[] mat;
private void Awake()
{
mesh = GetComponent<MeshFilter>().mesh;
mat = GetComponent<MeshRenderer>().materials;
}
void Setup(CropData data)
{
this.data = data;
mesh = data.Mesh;
mat = data.Material;
}
void DisplayTimer(TMP_Text timerUI)
{
timerUI.text = data.HarvestTimer.ToString();
}
}```
its kinda draft rn
but at least i found my direction
Do you really need a monobehaviour for this? Could just be a normal class and let a mono with actual functions do the hard work
just a random opinion but you might prefer to use a property for CropData so you can have it publically gettable and privately settable, then let whatever UI code you have just handle it directly without putting any of it in the crop script
You would usually want to copy the data here, so classes dont modify the SOs values
i mean unless they are modifying the mesh and material that seems fine, no?
ohhhh ok
nope
crop will have constant mesh/textures/materials, their "appearance" are immutable
Readonly?
i think property is fine
the "crop" object or the class is just a container for that, i want to set them up real time instead of spawning a whole prefab/object
There are more fields on the SO. It just becomes a pain later if you suddenly want to edit one instance of it, like one grows faster. Then suddenly you gotta go back and change the code
If you're sure none of these values will ever change then it's fine, but copying the values over is future proofing
i will copy them instead 👍
oh damn
yeah
because my game has boosters/buffs/statuses , so i need to +20% or -20% to certain attributes
How are you going to access all these crops?
A central manager for crops? Or just by object instance
i will have a central manager to store all the SO
yeah lol
If you're storing them centrally anyway why use a monobehaviour for storing crops on an object?
good question
i leave monobehvaior there only because idk if i ever wants to add something that require it
It makes sense here to use a monobehaviour
public class Crop : MonoBehaviour
{
private int ID;
private string Name;
private int HarvestTimer; // in seconds
private int Price;
private Mesh Mesh;
private Material[] Materials;
private void Awake()
{
Mesh = GetComponent<MeshFilter>().mesh;
Materials = GetComponent<MeshRenderer>().materials;
}
void Setup(CropData data)
{
ID = data.ID;
Name = data.Name;
HarvestTimer = data.HarvestTimer;
Price = data.Price;
Mesh = data.Mesh;
Materials = data.Material;
}
void DisplayTimer(TMP_Text timerUI)
{
timerUI.text = HarvestTimer.ToString();
}
}```
turns it to value copying instead
They said they're storing the SO in the central manager, not the crops created based on the SO data. The actual crop has to be stored somewhere. It probably needs to be associated with the actual GO too considering theres a price and harvest time.
The pascal case here is a bit weird, should be camel case
I mean there are multiple roads to Rome.
If it works don't touch it
🤷♂️ never said there wasnt either, all I said was using a monobehaviour makes sense. Dont really get the point of this message.
You are correct
I don't want to explain my exact idea so I cropped it in a small message
the whole system is still under draft maybe i will get back to u guys after few days
👍
🫡
public class CropData : ScriptableObject
{
[field: SerializeField] public int ID { get; private set; }
[field: SerializeField] public string Name { get; private set; }
[field: SerializeField] public int HarvestTimer { get; private set; } // in seconds
[field: SerializeField] public int Price { get; private set; }
[field: SerializeField] public Mesh Mesh { get; private set; }
[field: SerializeField] public Material[] Material { get; private set; }
}```
yeah its safer for this
ty guys
Are SOs that much of a game changer?
they are great for doing configuration or shared objects between scenes.
SO are good for objects that are immutable
I see, thanks
they can be mutated at runtime no problem but unity keeps the changes post play end 😐
basically a better data storage for data thats expected to have a base, constant value
ofc in a build these changes are not saved
So you could make a health potion item a SO
ofc
That's basically one way to store arbitrary data.
Definitely gonna have to learn how to use it then, about to add in items to my own game
lemme show u one usage
The SO itself would store things like the amount of health you gain, maybe a sprite/prefab representing the visuals. It's ultimately a way of storing data. So now you wouldnt have to define data in code or on prefabs. Much cleaner to see in version control changes as well
The actual health potion you see in game wouldnt be an SO, it would have data from the SO
its way easier for u to configure the data tho
@twin pivot
and if u can get the reference u can make use of all the data u saw
but u should not change the value in SO (the pics i posted) during gameplay tho
and its a easier workflow tho
imagine u have 100 kinds of health potions, you wouldnt want to make 100 prefabs right? when most of them sharing mostly the same scripts and do mostly the same stuff
u make an empty container prefab and swap/setup all the data from somewhere else
thats a way better technique my colleaque taught me, but whats different is that hes doing that in a .csv file and import it directly to the game code
im doing it with SO
they chose to use csv 🤮
u know why? because for one simple reason : dont want to create so much SO
fingers hurt
im not joking
well you can automate csv -> so creation/modification
or make your own editor window to edit all of them, ive done this to make importing data in bulk quicker
yeah i made a super rough version of this kinda thing in the past to help manage stuff in bulk
Oo very nice. I also make editor windows for colour editing
So like an alternative to using enums with switch statements
it can definitely do more than an enum
Enums on steroids then
SceneManager.LoadScene
how do i catch error if this function fail, want to run to a backup scene if it doesnt exist
if it doesnt exist
as in like, you typo the scene name or something?
i'd recommend you check out something that would prevent that happening to begin with, like SceneReferences
maybe the scene not existed yet, but just a fallback
not existed yet?
cant do try catch with this one
how would a scene not exist yet
This may be a dumb question but wouldnt using an equation for the variables and assigning value to the different items be better? Or is it just for easier customization
i plan to make that scene later, but i trying to find a way to check if scene loaded success or not
Just make a temporary scene and load that instead
no way to check scene success or not ? i think that would be useful
it would be much easier to just add something that would make checking this easier, like SceneReferences
is this outside unity, this one? https://github.com/starikcetin/Eflatun.SceneReference
Could also GetScene before trying to load it
yes that's what im referring to
im using scene name.. is there something similar to getscene but with string
GetSceneByName should show up in autocompletions after typing GetScene.
unity docs confuzled
Ive never seen that happen
It should. Make sure you have the using statement
Oh, the by scene name one. Yea looks like you can only do it by path.
the problem is u cant always define a equation for everything, and when u have the equation, meaning u need to change the value during some execution, its not suitable to stay inside the SO already
like i said, im storing "base value" thats shouldnt be changed
so even if im using the "equation method", i still need a SO for the base
i think i know what ur talking about tho
lets say u have
slime
lv1
atk : 10
def : 5
hp : 20```
```markdown
slime
lv30
atk : 50
def : 15
hp : 100```
u want to have an equation based on the levels to calculate the atk/def/hp so u dont need to create SO for lv30 slime right?
welp i wont make SO for lv30 either, only lv1
what i will do is : extract/copy the value of lv1, make the equation on the setup function
calculate from there
Ah i see, thanks
How do I make a custom button? Like doing X when left clicked and Y when right clicked?
I was using OnPointerClick, but doesn't seem to catch any event
Do I need an specific component on the object to catch the event or something like that?
you did not implement the interface
How do I do that?
IPointerClickHandler
then grab that interface's function and put that code inside
apart from that i dont see any issues
public class CustomClickHandler : MonoBehaviour, IPointerClickHandler
you're missing this
Hi guys, I have a project with a ray logic that registers the surface it hits, everything works fine in Unity itself, but when I make a build, the ray stops registering hits, what could be the reason?
I launch in Unity case and everything registers correctly with the statement in the console that the ray hit somewhere. But when I make a build, then in the dev version in the console my debug comments write that the raycast does not open anywhere
All scripts are saved, all scenes are saved, all layers in Unity itself work correctly
I have only 2 assumptions about what it could be, either the application itself is loaded, that the build can't count everything at the same time, or the beam is not output correctly when changing the resolution, but in the code I have a dynamic change in resolution creen.width / 2f, Screen.height / 2f, 0f and finding its middle, so idk
(The screenshots show the beam's operation logic)
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
A tool for sharing your source code with the world!
Still doesn't seem to work. Do I need something else on the editor for that to work?
is making an interact system for 3D third person view the same as 1st person view?
It depends on your vision of the system, what features you want it to have. It can be the same or different
Ok, so apparently it doesn't work if I add a Canvas component to the object they are in, but I need to modify the sorting order, shit
you implemented the interface correctly?
Yes, it does work on a isolated object
But it doesn't work on the element I want it to work due to the layout
Hi! I'm learning to program in Unity and I'm having trouble creating a parallax effect. I've followed all the steps from my programming class, but the background doesn't move. I'm sharing the code below:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public RawImage background, platform;
public float parallaxSpeed = 2f;
void Start()
{
}
void Update()
{
float finalSpeed = parallaxSpeed * Time.deltaTime;
background.uvRect = new Rect(background.uvRect.x + finalSpeed, 0f, 1f, 1f);
platform.uvRect = new Rect(platform.uvRect.x + finalSpeed, 0f, 1f, 1f);
}
}```
The idea is that the BG is on a layer behind the Button itself, but if I add a canvas component to modify the sorting, the EventListener does not catch it
can't you swap the order and remove the canvas? Have the button be the child of the BG
The bg is meant to be not showing while it's unselected, so I just dissable the object, but I guess, yes, I could, with some roundabout
Maybe add some logs to make sure that code runs at all.
better to just set the alpha to 0
i tried but this is the result and it doesn't help at all
could any of you guys help me debug this error?
public class Enemy : MonoBehaviour
{
[SerializeField] GameObject destroyedVFX;
[SerializeField] int hitPoints = 3;
[SerializeField] int scoreValue = 1;
Scoreboard scoreboard;
void Start()
{
scoreboard = FindFirstObjectByType<Scoreboard>();
}
void OnParticleCollision(GameObject other)
{
hitPoints--;
if (hitPoints <= 0)
{
scoreboard.IncreaseScore(scoreValue);
Instantiate(destroyedVFX, transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
}
}```
This doesn't tell me much. Share the updated code.
which line is line 20?
Start from reading the error and what file and line it happens on.
Here it is, i just added the debug
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public RawImage background, platform;
public float parallaxSpeed = 2f;
void Start()
{
}
void Update()
{
float finalSpeed = parallaxSpeed * Time.deltaTime;
background.uvRect = new Rect(background.uvRect.x + finalSpeed, 0f, 1f, 1f);
platform.uvRect = new Rect(platform.uvRect.x + finalSpeed, 0f, 1f, 1f);
Debug.Log("background uvRect.x: " + background.uvRect.x);
}
}```
this one is line 20:
scoreboard.IncreaseScore(scoreValue);
it happened to the file that is name Enemy.cs of which i've shared it along with the ss
Ok, so at least it runs, but looking at the output the uvRect.x doesn't change. I'd add the finalSpeed to the log as well.
that means that scoreboard is null. Do you have a gameobject in the scene with a Scoreboard script attached? And is it active?
here's alose a better view of each line in my code as well:
I'd suggest installing an IDE, like Visual Studio
well this is my Scoreboard script
really did try it but didn't work 😂😂😂
wdym by "didn't work"? Did you follow the !ide config guide?
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
• :question: Other/None
i found out that VS code uses lots of ram as i installed some features in it which obviously effects my computer (unity engine uses lots of ram + VS code too)
is it actually in the scene tho?
i added Debug.Log("finalSpeed: " + finalSpeed);
but this is the result
How much RAM do you have that you need to worry about it?
just a sec i'll check it and come back to you
i currently have 8GB of ram in my computer
Ok, so it's being 0. Is your parallaxSpeed field set to 0?
though unity works totally fine for me btw
yes, i tried changing that but ir won't move either
That should be enoughish for VS and the editor. Unless you're doing something really heavy.
Wdym by "won't move"? Where?
not really i'm only doing lightweight projects as i'm learning unity (i'm still a unity beginner)
Then VS should work just fine.
VS code would definitely be fine, but it might be more tricky to configure
wait i think you've inspired me to do something, if unity engine works totally fine and VS should be working fine too, i think i could be having some unnecessary softwares running in background 🤔
i mean the background, it doesn't do the parallax effect (srry if I don't express myself properly, i'm learning to program right now)
you mean the extensions?
Was there even an issue in the first place?
What extensions?
I mean VS or VS Code. These are 2 separate programs
VS code is by far the most lightweight out of the three (vs, vscode, rider)
So what is your parallaxSpeed set to?
no not at all it was all working fine at first both VS code and unity but later on it started consuming lots of ram (idk exactly why perhaps VS code itself or some random software running in the backroung)
VS code extensions
VS code
How do you know that? And was there an actual issue caused by that?
True but i chose to go with complete minimalism notepad++ (good it's not vanilla notepad) since something got messed up with VS code for me 😂😂
honestly i really don't know why exactly but all of the sudden VS code started consuming lots of rams i even tried to reinstall it but somehow there were some leftover files that i didn't know how to delete them
in other words i couldn't 100% delete it
do you have any advice @teal viper ?
How much is 'lots of ram'?
i'm making a 2D game where the background needs to move in a loop. The parallax effect is for making the background move. I set in on 0 rn
What's the issue with that? It's fine for programs to consume ram. Was it consuming more than 8GB and causing page swaps or something?
The best advice I can give: understand the situation before making decisions like deleting a program.
Ok, so how do you expect it to move if it's 0?
i tried to put 10 too but it didn't work
Was the log showing it being 10?
nope
well i'm using windows 11, the moment i start up my computer (not opening any software) as soon as i open Task manager i see that my computer is already consuming around 4 gb of ram, then i open a unity project that i have which also consumes 3GB of ram now opening VS code (which consumes 400-500Mb of rams) make my computer extremely slow in this case
i dont know why it didnt work before the logs but tysm
honestly i'm really still kind of new for unity and programming, i'll try to do this next time
Do you not see in the task manager what consumes the 4 GB?
i see
For my project which is quite large, most IDEs consume 2-3 gigabytes. 400-500 mb is nothing to worry about
8gb of total RAM might be a bit tight for modern unity development though. Best you can do is eliminate other programs using that ram
not really i can't tell exactly what's consuming that much of ram on startup is it the same for any of you?
true i'll try to upgrade my computer this summer as well
No. I can see what consumes how much memory. Where are you looking?
wdym?
Take a screenshot of what you see in the task manager
kk
here take a look
Chrome moment
Well, it adds up. I'm sure if you add up everything in the list + services and stuff, it should add up to around 7-8GB.
I wonder why you have both chrome and edge open though
any idea how to turn them off completely?
As well as using a third party antivirus and windows one.
i didn't even open edge today it gets opened by itself randomly (only sometimes though)
Might want to google how to disable windows feature to optimize RAM usage.
You also have node J's runtime running for some reason
perhaps better security? if one antivirus can't catch the malware the other would
Close unity hub too, you probably don't need it in the background. Perhaps Google drive too
there were times were i was opening 4-5 antivirus at once lol
I don't think that's how it works. Or that there is any significant improvement worth the extra memory and CPU resources used
i see thx for the advice
I see, in that case i should only keep windows vanilla antivirus open?
Also, if there's anything I'd worry about is your disk usage. That could definitely be a bottleneck.
Yes. Windows one should be enough, unless you explicitly surf suspicious websites and run randomly downloaded executables.
well there's nothing that is seriously important on my computer (perhaps except for my unity projects atm) do you think it would be a good idea to format it?
not at all, it only happened recently after i found that some people got hacked on discord (i already left the server)

