#💻┃code-beginner
1 messages · Page 800 of 1
i had an explicit example there that was not using +
i didnt see properly 😔 anyways i checked now it points to the right objects and instances
and this error is popping up too now
6000.0.46f1
maybe try the latest patch for 6.0?
that one in particular is probably an editor bug
or i guess before that, just check if you're getting it consistently after restart/library reset i guess
I am learning coding at tutorial unity and I copied that codes which unity said to copy. when i click play, it wont work
red :(.
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
i restarded and the eorror isnt popping up... i bet it will after a few more runs... i dont think its still related to my issue
stuck in this stupid bug for 3 days 😔
hum, which do i go with?
well obviously New doesn't work
you're using the old system, so maybe that's the right one 
console said it is missing component exception which there isnt rigidbody attached to cylinder with red warning
wait one sec
im dumb
thank you for much 🙏
@naive pawn bro bro
The thing is i changed yield return null to yield return waitforFixedupdate
and it worked because i am never changing my horizontal position via physics system so there is never contradiction in there
in this one
ok? you still shouldn't do intentionally do physics desyncs, that's just a trap for your future self lmao
ye 😭😭😭
because i am never changing my horizontal position via physics system
i don't think that matters, and physics would try to sync the entire transform.
it sounds like it "works" because with the WaitForFixedUpdate you're breaking it right before physics fixes it
just... don't
ok got it thanks 😭😭😭
yo is realistic voice chat hard to pull off as solo dev? like you know, different reverb at outside and different one inside some building or behind the wall etc.. im good at physics and im young math teacher but my experience with coding is little to zero
depends on how realistic you actually need it to be
i wanna make mil-sim game
it's enough of a problem to where i'd suggest at least considering if you actually need it
yes i need it v much
but you can find half measure solutions to it with more primitive checking
eg. seeing if someone is just being obscured, or if they are just in a different room
there’s this game called “Insurgency” and it’s my fav fps of all time but nowadays its dead and I feel like there needs to be a game like this with updated graphics - hardcore fps like Arma 3, but with tiny maps and no respawn - round based like A and B bomb sites.
so I think this vc thing is a must right?
but I dont know if I scope too big
no offense but based on how you are phrasing
scope is very too big
that kind of game needs a whole team of people who dont need to ask if scope is too big
ohh
well that’s unfortunate, I guess a bit of vibe coding wouldn’t work in such a game too right?
but is it still doable? I’m committed to spend 2-3 years for making 1 game.
honestly no
a game like that needs a whole team
what if I made cs 1.6 game and then just keep updating the graphics?
and mechanics too but slightly each time
that would be a lot closer to viable yeah
but unlikely to be a success if this is your first project
multiplayer is a pretty big thing to pick up and espicially in a context that requires super optimised and anti cheat based gameplay
is there no premade anti cheat that I can use?
the definition of "cheating" depends on your game
it's also not just the player inputs, but how your player logically acts - if they have information they aren't supposed to for example, that's also cheating
why it wont apply as transform?
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)
I literally make these codes with tutorial
it just doesnt work
in where? in player or smth
in your ide
follow the bot instructions maybe
the thing you code in
your ide is not set up properly, instructions to do so have been linked above
no 🥀
ok, then say so instead of blindly parroting
im sorry
an IDE is the app you code in, which is visual studio (vs) in your case
do these sentences make more sense now
your ide is not configured properly
configure it with the instructions linked above
I didn't rummage through anything
these are just git changes
eh I'll just git clone again, I'm not sure what I might have done
ok it is appearing on a completely fresh git clone for some reason as well... any clue what to do?
it might be nothing, but it seems it always goes wrong when I try to mess with git on my own
so I want to be safe
Can someone help me make a walking, running and jumping player (with wasd keys) and this is how I want it to look like:
what do you mean with that
what don't you understand
what specifically do you need help with
no one here will do it for you or will walk you through the entire concept step by step
if you have specific things you need help understanding thats where this server can assist
What does this image have to do with code
Why give "here's what I want my character to look like" when asking in the code channel
i want a walk, run and jump system
not more
please don't crosspost
https://www.youtube.com/watch?v=e94KggaEAr4&list=PLwyUzJb_FNeQrIxCEjj5AMPwawsw5beAy maybe this tutorial series will help
Learn the fundamentals of moving Characters in Unity3d with an introduction to character controllers!
This beginner-friendly tutorial is a thorough break down covering how we can move characters in Unity3d and explains the various options Unity has to offer: the built-in component, rigidbodies and custom character controllers!
SUPPORT THE CHAN...
I already searched for a video but it didn't work
What didnt work*
probably because you posted your image and asked how to move it
Yeah is that image supposed to be a 3d model or is it just an image?
I spent 3 hours working on the movement through all sorts of different tutorials, but none of it worked for me.
do you have some code to share
it is a image
So this is a 2d game?
@regal galleon for tutorials start with setting up your IDE
There's no command called
idea.
Idea 
There's no command called
idea.
Dawg
WHAT
!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
!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
Its not idea
😭
and than
I know I was flabbergasted at how I made the mistake twice
You havent actually asked anything concrete
We have no clue what you are doing where you have gotten stuck etc.
All you did was show us an image and say "i want a movement system"
This is not what this place is for
i dont know how to make one and a tutorial din't work for me
Try another tutorial
#🖱️┃input-system i think we should move that to #🖱️┃input-system
This is under the assumption they are failing at inputs
i dont know a single line of code and i am new to the program i use unity for only one day
Not that they are lacking some basic unity knowledge
Wow
Who could have called it! Me of course
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
@regal galleon highly recommend you start off with the learning pathways first
Does anyone have a file to share with me so i can download it
in thru one ear out the other lol
Please consider the bot link above, its a good start for learning unity
No and thats not how that works
Youre lacking some basic fundamentals of unity and you need to actually learn that first if you want to do anything
I promise you its a short step between that and a working character controller
but can you do it one time for me please i am new
No
why not
I cant and wont, listen to what im telling you
i am glad you asked here and not somewhere else for random files.. be aware that people might send you malware
Im not telling you these things for no reason
and next time you will ask for code on how to animate your model
no i swear i dont do that
And we dont even know if the game is meant to be 2d or 3d
lol bro stop, learn coding learn the basics and you will be able to master things on your own
there is a reaoson why people recommend you to do that
If you get the file now, you wont know how to use it
I see from your youtube that you are young, if you want to be a game dev you have to learn, it's sadly not as easy as getting code from others then telling the computer to "make the game"
It's not as easy as you assume, but it's also not that hard to learn. That's actually part of what makes game dev fun
3d
i dont have yt
So you want a 3d character controller for a 2d image of a character you dont have a model for?
I think this person is really young and has a misunderstanding about how game development really works
Bro please help me for once
thanks
So you're good now? Don't need any more help?
yes
If you say so
I give him 10 minutes
Generous 😭
why
Oh no reason, good luck
i dont mean to ask the same question twice but does anyone know how to recreate the simple noise node in csharp? I just need to know the y-positions that it produces on a shader graph
Noise is deceptively complicated for being so widespread in game dev
I would suggest downloading a noise library
But if you do want to create your own, I think I have a resource for you
would it be easier to recreate those noises in csharp? how would i go about doing that?
pray tell?
By noise library I mean like installing a package in unity, so it's someone elses code. Writing your own is harder
Ill pull it up
let me mention that im not trying to recreate a shader graph, i need my player to walk on the shader graph so i need to use a noise that i can recreate in csharp for the code
honestly i dont see the benefit in not using a preexisting library
So you mean you want to be able to use the same noise texture that you use in your shader in your c# code?
no, i want to use the noise in the shadergraph (to make realistic looking waves) and then recalculate the y points that shader graph creates so my character can walk on them
basically, i need to know how the noise calculates y values so i can mimic them in physics
well yeah then the shader graph noise wont be of use
iirc theres no way to expose its math in any usable way
i dont think its deterministic
damn.... should i just use gerstner waves then?
My best guess would be to actually generate the waves in C# but using compute shaders, saving that to a texture, then feeding that texture to the shader graph to turn that texture into waves.
That is a complicated task but possible
its complex but not nescessary
you could use a custom hlsl node
and feed the parameters from the c# code at runtime
so they match
oooooo, just to be clear: are you saying to only generate the waves in c# once, save the produced texture, then recreate just the y points in c# going forward?
Oh yeah that's way better lol
Nah scratch my idea
oh okay lol
my way is a bit more work but it might be better in the long term
kuzmo suggested creating your own mathematical function to sample waves given an input x and z, then to use that function in C# land and in shader graph land.
how would i go about doing this? also, do you think it'd be better than just using gerstner waves?
but that means you will need both a. c# code to generate the waves and a hlsl node for the exact same things, then you take your own parameteres from the c# script at runtime and feed them into the hlsl node's serialized values
okay, i think i can do that (its basically just what i was doing with gerstner waves but with my own custom wave function)
so basically in your shadergraph you just have to swap out your current noise node for the custom one and then expose the parameters
then make sure your c# can access those parameters and change them dynamically
this should work and be pretty performant
iirc i do something very very similliar in my own project but i use it to recreate random pattern on my enemies using a wave based noise
that's so cool
#🏆┃daily-win message this was the end result
anyways its not too disimilliar to what you need to do, i would start by looking up if anyone created a c# script for the wave or even an hlsl node, that would be a good start.
awesome, i think i already know some places to look for that! thanks so much, ill definitely be back with more questions later!
good luck :)
thanks dawg, ill need it
ah, you found out about gerstner waves – I should've mentioned those to you earlier
they're very nice, and the math isn't that bad
Hey, I have a huge problem with my programming. My quest just won't progress and I have no idea why. Could someone help me? It's for my semester project, which I have to hand in tomorrow night. I'm not desperate, please, dear Unity God, hear me.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
I don't know what to do, I'm a complete beginner.
Share the relevant code so we can help...
we can't help without more info
this looks pretty good
the hardest part of it was actually making the 3d noise stick to the skinnedmeshrenderer
The problem is I don't have any nitro, so I don't know how I can share it with you.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
or here
copy the code, paste it in one of the links provided. Hit save, share the generated link
Oh thats a skinned mesh its on ? interesting..
There's no command called
screenshot.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
wow thats a first
@visual idol
are we talking about the same thing here, i was talking about the patterns on the enemies lol, unless youre thinking of the screen radar thing
oh yeah I meant the noise / feedback radar thing
oh that was pretty simple actually, uitoolkit stuff
no shaders
done entirely with like 2 scripts
I'm interested because I am yet to do that much with UITK apart from play around with it
ill start a thread in #🧰┃ui-toolkit
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
my game home
A tool for sharing your source code with the world!
You should addmore logs, or even better code editor break points and see where the code is failing
// 6. Brief an der Bank (JETZT WIE DIE BRÜCKE)
questTMP.text = "Untersuche den Brief an der Bank";
if (quest.briefOma != null)
{
quest.briefOma.SetActive(true);
Interactable interBank = quest.briefOma.GetComponent<Interactable>();
if (interBank != null) interBank.onInteract += () => { NextStep(); };
}
questWeiter = false;
while (!questWeiter) yield return null;
// 7. Blumen (WIE DIE BRÜCKE - Anklicken)
questTMP.text = "Pflücke die Blumen für das Grab";
foreach (var blume in quest.alleBlumen)
{
if (blume != null)
{
blume.SetActive(true);
Interactable interBlume = blume.GetComponent<Interactable>();
if (interBlume != null) interBlume.onInteract += () => { NextStep(); };
}
}
questWeiter = false;
while (!questWeiter) yield return null;
// 8. Grabstein (Finale)
questTMP.text = "Bringe die Blumen zum Grabstein";
while (!quest.grabStein.GetComponent<Grabstein>().hatInteragiert)
{
yield return null;
}
// 9. Ende
questTMP.text = "Schnitzeljagd beendet! Gut gemacht!";
}
} // Diese Klammer schließt die Klasse (Fehler CS1513 gelöst!)
aba ihr geht er nicht weiter und ich weis nicht warum soory mein englisch ist echt nicht gut und ich weis gerade wie ich antworten soll soory
That’s why my code doesn’t continue anymore, I can’t collect the flowers, the bank works, but it stops when going from step 6 to 7, and my English isn’t very good.

if you sent the links not sure why you pasted the wall of text tho
we can see the code, but still if you think something breaks down somewhere debugging is part of fixing something and first steps you should take
hard to know what those names mean without being in english tbh
I'm guessing Interactable is what supposed to grab flowers?
by
the bank works
what exactly do you mean ? in what sense it works
I think the design of this being a coroutine that waits is bad and has contributed to your issue
You could store state in a better way and re execute something to check the next part instead.
You already use an event to handle the interaction so you already understand this
yaquestWeiter is sketchy where does it supposed to set tru
this is a coding channel..
Oh oops most of my problems are coding so just habit my bad
polybrush is dead so id just learn to sculpt in blender if you already can use it a bit @mint imp
the original maker of polybrush / probuilder usually hangs around in #🛠️┃probuilder
It needs to be revived the mesh placing tool is super useful
Poly brush... died
thats so unfort
The mesh placing tool is the entire reason i switched to it from blender
Yea the docs say "The Polybrush package is deprecated and no longer supported in Unity 6.3 (6000.3) and later. "
not sure why they just gave up on it
Just add better tools to place prefabs and meshes in the engine ffs
soory mom pleas
"i am collecting the letter, and it’s actually supposed to open a ui panel (an image i already made in unity). but right now, it just collects the item and doesn't progress to the next quest. in the next quest, i need to collect flowers and put them on the gravestone to finish my game."
as suggested you should use events for each action taken, doing a wait is sketchy
We dont know anything else apart from the code shared so you need to be more specific.
Is this the part where its "waiting"?
questWeiter = false;
while (!questWeiter) yield return null;
withing for my dialog
sorry is that a yes or no?
end withinf for my items blume brief
we cant really help you if we litterally cant understand what your code says
are you getting this log
Debug.Log("QuestManager: Signal erhalten!");
"should i stream my screen so it's easier to understand?
no
no, there are intentionally no vc's here
that would hte exact opposite here
you can use screen recordings if you think that'll help illustrate
Im having an issue with rotating my player to match camera but limiting the player rotation.
This function just lerps my players rotation to face the same way the camera is pointing
(Its a 3rd person spaceship for context)
How can i make the player follow the camera EXCEPT keep x at 0
but how ive tried that in every way i can imagine and the behavior is weird
well we can't guess those ways, you'd have to show them
okay let me whip one up
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
public class MonsterControllerV2 : MonoBehaviour
{
public NavMeshAgent ai;
public Transform player;
public Camera playerCam, jumpscareCam;
public float aiSpeed, catchDistance, jumpscareTime;
public string sceneAfterDeath;
private Animator mAnimator;
private Renderer rend;
void Start()
{
rend = GetComponentInChildren<Renderer>();
mAnimator = GetComponent<Animator>();
}
void Update()
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(playerCam);
float distance = Vector3.Distance(transform.position, player.position);
bool visible = GeometryUtility.TestPlanesAABB(planes, rend.bounds);
if (visible)
{
ai.speed = 0f;
ai.SetDestination(transform.position);
}
else
{
ai.speed = aiSpeed;
ai.SetDestination(player.position);
if(distance <= catchDistance)
{
player.gameObject.SetActive(false);
jumpscareCam.gameObject.SetActive(true);
StartCoroutine(killPlayer());
}
}
}
IEnumerator killPlayer()
{
mAnimator.SetTrigger("TrJumpscare");
yield return new WaitForSeconds(jumpscareTime);
SceneManager.LoadScene(sceneAfterDeath);
}
}```
Here is the script that I am using for the monsters movement. I want to add a system where if the player is looking at the monster for too long (for example 5 seconds) the monster will teleport to a new location. I want this location to be the same distance that it was away from the player before teleportation however I want it to be somewhere else around the circumference of the player. what would the simplest/ easiest method of doing this be for a beginner?
do we care about colliding with walls etc?
Random.insideUnitCircle ?
!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/
📃 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.
Maybe im not understanding
Transform.rotation vs Quaternion.Euler(rotation)?
could you elaborate?
the lerp cares about your 0
nvm i misread your Q.
but yeah you should state if you want to spawn it outside / behind walls etc.
also post your code with links from sites here #💻┃code-beginner message
NEVER touch stuff like transform.rotation.z
you are getting confused between rotations that are expressed as sets of Euler angles, which are x, y, z
and Quaternions
Quaternions have x, y, z, and w and they ARE NOT EULER ANGLES
they cannot be used as euler angles
you are best served forgetting they exist
Can you explain what you're trying to do with this code?
transform.rotation is a Quaternion, it is not a set of euler angles
are you just trying to get a "flat" version of the rotation of the camera?
Like, so your player can move in the direction of the camera but without going up or down?
If so, do this:
Vector3 cameraForward = cameraRoot.transform.forward;
Vector3 flatForward = Vector3.ProjectOnPlane(cameraForward, Vector3.up);
Quaternion targetRotation = Quaternion.LookRotation(flatForward, Vector3.up);```
(this is assuming a universal "up" direction)
you explained something about planets so we might need to get a little fancier
is that the case?
@misty sand
basically what i would do, assuming this is 3D.
Vector3 origin = player.position;
float distance = 5f;
Vector2 randomDirection2D = Random.insideUnitCircle.normalized;
Vector3 spawnPosition = origin + new Vector3(
randomDirection2D.x,
0f,
randomDirection2D.y
) * distance;```
that *should * work, I think
I have a parent object that maintains a distance around a planet, and orients itself so "forward" is aligned to the horizon.
I have 2 children that can rotate freely
A camera root
and the actualy spaceship
The camera can look around left and right, up and down (Respective to parent object)
Right now the spaceship follows that movement
Whiche allows you to "look down" and fly towards the planet
I want the spaceship to rotate left and right with the camera, buy not look up and down.
My movement is based on which direction the spaceship is facing, so looking down gives unwanted results
where is the timer which will run that code if the time condition is met?
you have to seperate your issue into smaller pieces. Start with the player looking at monster too long function
timer?
is the "parent" the spaceship?
The parent is an empty that acts as the core
Just handling the positon of the player
The spaceship and cameraroot merely rotate from that point
Can't you just use the parent object's orientation then?
like:
Vector3 cameraForward = cameraRoot.transform.forward;
Vector3 flatForward = Vector3.ProjectOnPlane(cameraForward, parentObject.transform.up);
Quaternion targetRotation = Quaternion.LookRotation(flatForward, parentObject.transform.up);```
Hmmm let me look into that
I swear there was a reason i didnt
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
public class MonsterControllerV2 : MonoBehaviour
{
public NavMeshAgent ai;
public Transform player;
public Camera playerCam, jumpscareCam;
public float aiSpeed, catchDistance, jumpscareTime;
public string sceneAfterDeath;
private Animator mAnimator;
public float currentTime;
public float TimeLimit = 5.0f;
private Renderer rend;
void Start()
{
rend = GetComponentInChildren<Renderer>();
mAnimator = GetComponent<Animator>();
}
void Update()
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(playerCam);
float distance = Vector3.Distance(transform.position, player.position);
bool visible = GeometryUtility.TestPlanesAABB(planes, rend.bounds);
if (visible)
{
ai.speed = 0f;
ai.SetDestination(transform.position);
currentTime = Time.deltaTime;
if(currentTime >= TimeLimit)
{
}
}
else
{
ai.speed = aiSpeed;
ai.SetDestination(player.position);
if(distance <= catchDistance)
{
player.gameObject.SetActive(false);
jumpscareCam.gameObject.SetActive(true);
StartCoroutine(killPlayer());
}
}
}
IEnumerator killPlayer()
{
mAnimator.SetTrigger("TrJumpscare");
yield return new WaitForSeconds(jumpscareTime);
SceneManager.LoadScene(sceneAfterDeath);
}
}``` ive added the timer system now i just need to teleport the monster to the transform
currentTime = Time.deltaTime;
if(currentTime >= TimeLimit)```
that logic is not right
This is a function in my parent object that handles keeping the entire gameobject level with the planet surface
it doesnt rotate with turning, because thats what my cameraroot is for.
Im already rotating spaceship with parent to a degree
but when i want my spaceship to face towards the camera for turning the ship and always moving forward thats when i need it to follow my camera (which is also rotating with gameobject inherently)
Which object is this code on
yeah i just realised and fixed it
{
ai.speed = 0f;
ai.SetDestination(transform.position);
currentTime += Time.deltaTime;
if(currentTime >= TimeLimit)
{
}
}
else
{
currentTime = 0;
ai.speed = aiSpeed;
ai.SetDestination(player.position);
if(distance <= catchDistance)
{
player.gameObject.SetActive(false);
jumpscareCam.gameObject.SetActive(true);
StartCoroutine(killPlayer());```
what does that line do
bool visible = GeometryUtility.TestPlanesAABB(planes, rend.bounds);
it checks if the monster is in the players view
it's checking if the renderer's bounds is inside the camera's frustum
it's not perfectly accurate but is decent
The parent gameobject
No matter where the object is it will align with horizon
Then the rotation of my ship and camera are just local rotations
ok well the code I shared should work
because your code is setting the up direction
notably though your code is only really setting the up direction of the "root", not the forward direction.
what do you mean?
what would you of done differently out of curiosity?
it's all based on AABBs, there will be some cases where the edge of the bounding box is just barely in the frustum and you'll get a true result even if the player can't actually see the thing
I wouldn't necessaarily do anything differently
it depends on your requirements
this is a fast approach
if you need more accurate results you'd need to do something a little more complicated like testing a collection of predefined points within the object's mesh itself
you could probably make "key points" placed on places like each hand, feet etc..
then check those with some type of Dot product or something.
takes more work tho
or a raycast
it was just the first method i saw to achieve my desired function, the game im making is only a small 4 week project for college so it works well enough for me.
true ray or bigger cast might be better to be precise / behind walls. Id use dot too for angles
did you implement the Respawn code ?
Yes it did work thank you so much!
what do you mean?
I want this location to be the same distance that it was away from the player before teleportation however I want it to be somewhere else around the circumference of the player. what would the simplest/ easiest method of doing this be for a beginner?
ive only set up the timer so far, still trying to figure out how to do the teleport part
well code I sent, if works gives you that position, just apply it to whatever it is you're using
do you think you could explain it slightly, im still trying to learn c#
its a simple assign operation
usually =
mything.postion = newPosition
if you're using navmesh agent you probably need to do agent.Warp because navmesh overrides Transform
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.Warp.html
if gives issue, you might have to do A samplePosition first and pass that to warp
(and possible Stop the agent first if its in motion)
yeah i am using a navmesh
{
ai.speed = 0f;
ai.SetDestination(transform.position);
currentTime += Time.deltaTime;
if(currentTime >= TimeLimit)
{
float currentDist = Vector3.Distance(transform.position, player.position);
Vector2 randomDir = Random.insideUnitCircle.normalized;
Vector3 dreamPos = player.position + new Vector3(randomDir.x, 0, randomDir.y) * currentDist;
NavMeshHit hit;
if (NavMesh.SamplePosition(dreamPos, out hit, 5f, NavMesh.AllAreas))
{
ai.Warp(hit.position);
}
}
}```
does this look good?
try it
you might need to reset timer as well
it doesnt appear to be working
i can look at it for however long i want without it teleporting
ill send the current code
check console and also put logs make sure no errors / warnings
im not getting any errors or warnings, can i send the code as a ss cus i hit the character limit
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
https://paste.mod.gg/ktsxqqxnnkvd/0 did that work?
A tool for sharing your source code with the world!
putting logs inside blocks where conditions must be met is important to verify code is reaching there
what line should i put a log?
start with the visible bool
is this bool even true , so as nav said use a bool right after you enter the scope
so the time is working but the if statement straight after isnt
yu mean NavMesh.SamplePosition
reset the timer otherwise your code inside the if statetment will be executed permantently
{
Debug.Log("working");
float currentDist = Vector3.Distance(transform.position, player.position);
Vector2 randomDir = Random.insideUnitCircle.normalized;
Vector3 dreamPos = player.position + new Vector3(randomDir.x, 0, randomDir.y) * currentDist;
NavMeshHit hit;
if (NavMesh.SamplePosition(dreamPos, out hit, 5f, NavMesh.AllAreas))
{
ai.Warp(hit.position);
}
}``` this part doesnt run apparently
so Debug.Log("working"); isnt printing?
also log is missing in SamplePosition if statement to see if it even gets there
its not printing, how would i write it with in sampleposition?
currentTime = 0; this should be inside the IF current > Limit
otherwise your'e setting to 0 on the Next frame never reaching TimeLimit
so how would that line look?
I mean the same way you wrote the other one lol but yeah try this ^
wdym, its the same line of setting it to 0 but inside the block that timer has reached
you put it outside of it
oh yeah
so it going current += in one frame then right after sets to 0 and keeps going
should it go after the warp?
like the last line in that if statement ( the currenttime >= one)
as long as inside here
if(currentTime >= TimeLimit)
{
.....
}```
"timer reached, good set to 0 we don't need you right now "
{
Debug.Log("working");
float currentDist = Vector3.Distance(transform.position, player.position);
Vector2 randomDir = Random.insideUnitCircle.normalized;
Vector3 dreamPos = player.position + new Vector3(randomDir.x, 0, randomDir.y) * currentDist;
NavMeshHit hit;
if (NavMesh.SamplePosition(dreamPos, out hit, 5f, NavMesh.AllAreas))
{
ai.Warp(hit.position);
}
currentTime = 0;
}```
like this?
it doesnt matter if its on the first line or last line, as long as its that block. Its all happening on the same frame
finally
there are no early return so all those lines will run, even if Sample is run
@rich adder i gotta say i really appreciate the help. im sorry for all the questions but after this conversation im sure you can definitely tell im new to coding and unity. thank you for sticking with me and not giving up!!
no worries, we all been there at some point 😛
is the teleporting working
yeah it is, the only weird thing is that the debug message will run in the console but it wont teleport 100% of the time
ill send a vid to show you
I'm assuming the condition to teleport is cs if (NavMesh.SamplePosition(dreamPos, out hit, 5f, NavMesh.AllAreas)) { ai.Warp(hit.position); }so a valid sample position would need to be availble for it to warp the ai.
ya you could also add log there too and be sure 100% is either running the warp or not at all
5f is a pretty generous distance but you could also verify what dreamPos is if you use a DrawLine or something
wish we had a Debug.DrawSphere
anyway Debug.DrawLine(transform.position, dreamPos, Color.Red, duration: 5f) before If(SamplePos)
as you can see sometimes it doesnt teleport. i would also prefer it if it teleports out of the players view but its not a neccesity if its too complicated for me to understand
the not in view thing could be easily done with some sort of loop , keep testing if new pos is where you want if not keep trying
add additional check, either the fustrum thing or dot prod could work too prob
as to why its not doing newpos every time , you need to check the logging I suggestion above
i added the debug for the red line and it did this when not teleporting
looks like its putting new pos in the ceiling somehow
it also made a line when the teleport did work
dreamPos = player.position + new Vector3(randomDir.x, 0, randomDir.y) * currentDist;
I think issue might be stemming from adding playerPositions y pos * dist
if player is at 2f and you do 2 * 5 you get 10, a very ceiling pos lol
with terrain like this it gets tricky, I assumed it was flat ground at first
so what do you think the best thing to do would be?
how about a list of Vector 3 you define in your inspector and then randomly place your enemy on one of these
what would this look like?
nah I'd do maybe
Vector3 horizontalOffset = new Vector3(randomDir.x, 0f, randomDir.y) * distance;
Vector3 dreampos = new Vector3(
player.x + horizontalOffset.x,
agent.transform.position.y,
player.z + horizontalOffset.z
);
``` forgot the names so i renamed it
and you would need put it in some sort look and test first if its within players view, if it is keep trying
dot product should work fine enough i think
might stil be an issue tho with the agents Y pos
perhaps you could sample the terrain / ground first and use that Y
like sample it from high enough Y down to ground with a ray, then use that Hit pos's Y only on ground layer
Hey I have to go gym so I won’t be able to do anymore to the code for a couple hours. I’ll try what you said and do you mind if I dm you if I have any more issues?
eh I have my DMs closed, but you can tag me here any time/ even better start a thread
but yeah I think 100% ray down is the way to go
Yeah okay all good. I think I’ll tag you. Thanks again for all the help you’ve given I really appreciate it
hello
im using the current
Physics.simulationMode = isToggled ? SimulationMode.Script : SimulationMode.FixedUpdate;
to handle pausing/unpausing physics, however when i pause physics, raycasts seem to break. is there any reason/fix for this?
(second recording is just to show that when physics is always enabled nothing goes wrong)
I wonder if manually syncing transforms to physics would fix this but yea seems odd that simulation being manual would stop raycasts working (or atleast giving any results here)
Does anyone know how i could pixelate jus these shadows?
thank you, that did work
Awesome. There is a setting for this to be done automatically and i presume this happens each physics update hence this causing this behaviour
interesting, if i have any more issues i'll look into that
do you have a script thats actually responsible for simulating physics? because to me this makes sense why stuff would break if you just set it to SimulationMode.Script while not actually doing anything
i basically just wanted to disable any physics from happening, so i dont have anything responsible for simulating physics
not sure if you'd run into any other odd cases then. if it works thats cool but it seems like a very odd solution to this problem
if you have any suggestions i'd be happy to try them, but what rob suggested is working for me and im not going to be messing with physics any further than this requirement of it being turned off and on
my first thought would be to have some event responsible for notifying when physics is toggled on/off. any object can listen to the event and set the rb to kinematic or non kinematic
but yea still if your setup works with no issues down the line, then 🤷♀️
i do find it very weird that syncing transforms fixes that considering those objects aren't moving
what's the Unity.Physics (DOTS) equivalent to this code snippet? I can get the collider through an entity's PhysicsCollider component but it doesn't seem to have any bounds?
Depends if the platform is rotated or the camera is 🤔
what shape is the collider?
no
it cannot be cast to CapsuleCollider
that's a totally different physics engine
hey so here im using a coroutine to add a delay between the shots being fired to prevent spam , is this efficient or is there a better way
dont mind the sneeze btw

It's possibleSo, the Unity physics equivalent of Bounds is this: https://docs.unity3d.com/Packages/com.unity.physics@1.0/api/Unity.Physics.Aabb.html
I'm trying to see how to get an AABB for a collider now
Definitely don't want to use coroutines for that sort of thing. Track cooldowns in update, so that you can interrupt and manage them easier.
elaborate
Lol
Oh here's hoiw you get the AABB for a collider in unity physics:
lol?
coroutines won't give you an accurate cooldown, and no it's less efficient
Using a timer variable in Update or FixedUpdate is the best way
how do i do that , do i just create a variable and set it to increase by 1 value every second and then use it to delay the shooting?
cus this is what im doing rn
something like this:
float timer = 0;
public float shotsPerSecond;
float shotInterval => 1f / shotsPerSecond;
bool fullAuto = false;
void Start() {
// start off primed and ready to shoot
timer = shotInterval;
}
bool ShootInputPressed() {
return fullAuto ? Input.GetKey(KeyCode.Space) : Input.GetKeyDown(KeyCode.Space);
}
void Update() {
timer += Time.deltaTime;
if (timer >= shotInterval) {
if (ShootInputPressed()) {
timer -= shotInterval;
Shoot();
}
else {
timer = shotInterval;
}
}
}```
wowy i need a minute
can u explain this line? "float shotInterval => 1f / shotsPerSecond;"
bool ShootInputPressed() {
return fullAuto ? Input.GetKey(KeyCode.Space) : Input.GetKeyDown(KeyCode.Space);
this too
? : is a ternary operator
basically a one line if else statement
ye but whats the diffrence between the GetKey and GetKeyDown
oh GeyKey is true as long as its held, GetKeyDown is basically a "one shot" even if held only triggers once until pressed again
ooooooooh
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
oop sorry
are you asking about => ?
i dont understand the whole line , like the purpose of it and what does it do
and that too
=> makes it a get read only property, get/setters are functions basically that run when you access a property.
so everytime you access shotInterval it calculates the interval based shots per second
(so you wouldnt be able to modify the shotsPercond manually somewhere else in code, and there is no need to)
can someone please help me figure out why my enemy isnt flipping when the player enters the back collider? the enemy script is attached to the main Enemy game object, and the EnemyAI script is attached to each of the front and back collider game objects
Enemy script: https://paste.mod.gg/afitpicjwiyl/0
EnemyAI script: https://paste.mod.gg/wjjojimxprht/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
the detecting for if the player is in front/behind works btw just not the flip logic
the flip method works too since I use it for walls
oooh so basically instead of storing shotsinterval it just calculates it on the fly whenaver we access it right?
whats the layer on the flippy things collider
Everything apart from attack collided is Enemy
basically you're doing
float get_Number()
{
return something / somethingElse;
}```
fields / variables are the ones stored
imma ask smth but lowkey dont flame me for it , what does return do :3
returns out of a functions , they all require it unless the function returns void
if done in a void it just stops or return out the function
but you don't return a value, like the others do
so this returns something by somethingElse
like is this the math / or is it smth else
yea this function just returns a simple division operation
best take some c# courses they cover most of this
daim now i sound stupid 
final question , in the code he provided how do we control the amount of shots per second
i used to program with C++ but with arduino
but then you should know most of this, they are similar in many ways
you make it a inspector value you can modify in inspector
not rlly , most of the stuff we use in arduino has nothing to do with these (atleast the stuff i've done)
alr ty
I mean the c# stuff not unity
I mean C++ / C has return values lol
oh no thats an entirely diffrent thing
surely you used return before
i just never understood them
even tho its just a simple thing that returns a value from a function
ya in this case the name literally explains it straightforward lol
fr
imma go back to unity now
ty for the help
(lowkey dont tell the other ppl here im stupid cus they still dont know that
)
eh no reason to put yourself down, its important to ask what you're confused on. suggesting doing the basic courses isn't implying anything negative on you, it helped us all reach where we at now
hey, can you guy gimme me some help? I don't want to use anymore ai chatbots to help me with my game so I am gonna talk with other human beings, I know, incredible
anyway here is the code that gives me nightmares:
public UpGradeSO getRandomSO()
{
int random = Random.Range(0, upgrades.Count);
UpGradeSO randomSO = upgrades[random];
if (randomSO.requiresUnlock)
{
if (!abilitiesOBJ[random].GetComponent<Abilities>().unlocked)
{
return getRandomSO();
}
}
if (!upgrades[random].stackable)
{
upgrades.Remove(upgrades[random]);
}
return randomSO;
}
now what I want it to do I get a random scriptable object for an level up/upgrade system, and this little function gets a random scriptable object off a list, but I wanted it to check if the ability is unlocked, and if not, don't give a scriptable object that requires to be unlocked
I know, this code is a** and for some reason, instead of returning a new scriptable object when its required to be unlocked, it jusst returns null, please send help my brain decided to soft lock itself and I dunno what to do
recursive function are pretty dangerous, you should really only do it when you have a proper "escape"
if (!upgrades[random].stackable)
{
upgrades.Remove(upgrades[random]);
}``` pretty sketchy
imagine you have
If upgrades.Count == 0, Random.Range(0, 0) gives you:
index 0
but there is no element 0
so randomSO ends up null
Is it fine to keep my camera code in the same script as the player movement?
I have it all in a playercontroller script right now
if its easy for you to know where to find it, thats all that matters
generally you want different components per responsibility
Yeah it is. I even have regions in the script set up to seperate the camera and movement
in the beginning though its acceptable, but monoliths quickly scale and become unmanageable
especially debugging
Yes exactly this
Until it starts becoming unwieldy, not a problem
So the only value that is important for both scripts is the moveSpeed (relevant for the aiming which slows me down). How could I reference that value in the camera dedicated script?
alr dude tysm , imma be using this code from now on , i just implemented it and added the fullauto toggle and daim ngl thats awsome
make it public, or idieally a public get-only property
though an event might work better
Copy the collection and remove elements that do not qualify. Then select a random object and return that object instead of randomly selecting objects till you get a valid object - potentially infinite.
Hello, everyone.
I’ve been trying to find a suitable algorithm for checking the ground under the player’s feet for two weeks now, and I haven’t come up with anything.
Let me explain: to adjust the player’s direction of movement, I need to get the surface normal (as in all tutorials), but SphereCast/CapsuleCast at the edges give the normal in the direction of the point of contact, not the real one. Because of this, the player “slides down.” The effect is shown in the image below.
This isn’t the first time I’ve seen this in various controllers, but I don’t like this effect. I’m guided by games such as Quake, Half-Life 2, and Portal 2, where this doesn’t happen.
When studying the above games using the console, I discovered that they used BoxCollider instead of CapsuleCollider. However, I am told that no one does this now, although I do not understand why.
In general, please point me in the right direction. I cannot yet figure out the best course of action on my own, as I have little experience in game development.
Thanks in advance!
Hi, does anyone know how I can make a vehicle destruction system based on states? For example, we have our car separated into different parts, each part with a certain amount of health. When the car is hit in one of those parts, the part loses health. When it reaches a certain health level, the part's model changes to a bent version, until it detaches from the car, maybe using triggers and prefabs??? if anyone knows about an existing tutorial or something i can check it would be very useful
what exactly are you asking about though ?
wdym
there are multiple things you have to do but are you asking about checking the value ? spawnning
damage ?
i mean, i want to know first if there are guides already existing on this topic, ive researching and found nothing
then there is probably nothing, you're asking a very specific problem which has many different solutions. generalize what you want and you can find more stuff
instead of "how to do exactly xyz" "how to do x" then "how to do y"
then put everything together
ok
Start with the health system, and log / do something when within specific range. This is an easy thing to start with
"how to map number based on specific ranges C#"
if else statement, a dictionary etc..
many solutions
var results = new List<UpGradeSO>(upgrades);//GC: pool instead and avoid having to differentiate
for(int i = 0; i < results.Count;)
{
if((!abilitiesOBJ[i].GetComponent<Abilities>().unlocked)
results.RemoveAt(i);
else
++i;
}
if(results.Count < 1)
return null;//Or throw an error. There weren't any valid objects.
int random = Random.Range(0, results.Count);
var randomSO = results[random];
if(!randomSO.stackable)
upgrades.Remove(randomSO);
return randomSO;``` @hoary nova
But personally, I would rather just have a single collection that references both upgrade and ability.
What's a public get-only?
public float MoveSpeed { get; private set;}
Oh
only the movement script for example can modify it
but every script can read / use it
you dropped your private set;
!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/
📃 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.
(unless this is an interface)
oh true
is this clean readable optimized 6"3' feminist muscular code or nah
https://paste.mod.gg/ovwpmixfwqyo/0
A tool for sharing your source code with the world!
i usually link it to a field MoveSpeed => moveSpeed [SerializeField] private moveSpeed
hit save, send generated link
I often do a {get; private set;} and combine that with [field: SerializeField] if needed
I like to avoid explicitly doing a backing field if possible because of it being easy to refer to both inside the class
but yea if you want a public getter only that works too
true.. I once saw something with naming, tbh I don't quite remember if it messed with anything
yea the backing field does have a prefix making it hard to change it to a plain field later but i dont mind that
We can work around that with formally serialized as like any other rename
oh okay thats pretty tame then
Oh yeah I have to modify the moveSpeed in the camera script. Right now I've ended up with this:
It can certainly be better right
A potential unwanted behavior would occur if the timer had exceeded the interval but a shot was not pressed. You'd have to wait till the timer exceeded the value again before being able to shoot.
huh why would the camera have control on moveSpeed?
thats not its responsibility
Because I've tied the "Aiming" mechanic to it, and in that I reduce the movement speed when it's active
thats bad
the Movement script should modify through a method getting called, or event
But i have it set so as to where if the button isnt pressed it sets timer=interval
Ah right, my mistake. Normally folks would have set timer to zero here. Gotcha.
Its in the else of the if function
Yeah I might just stick with a single script for now
No worries dude, ty for taking the time to read my code ❤️
if you press a key for "Aiming"
the script that handles that should fire an event, then camera, or other scripts interested in that being active or not modifies a value.. pretty easy and keeps thing from being spaghetti
imagine you have an Icon that shows up when you're scoped in ? / aimed or something else needs to happen, now you're gonna have huge amount of code controling UI too or if you have multiple scripts you got all sorts of spoons in that soup, like camera controlling UI now?
a centralized place where different scripts can find a common value, easy. Yes it can be done with monolith but then debugging will be a mess and not very extensible
So instead I should handle the movement part of the aiming mechanic in the movement script and the camera part in the camera script?
just something that process what your inputs do
if you have public void ChangeMoveSpeed(float amount) { moveSpeed = amount; }
then your Inputs or anything can change it by just calling that method, the movement script shouldn't care where from, it only cares it needs to change movement speed and handle movement code
you can make the value public but then you can't know for sure it was changed, and most times you do to react elsewhere based on it
hello all, i want to make a manual blinking mechanic in my game. if you dont blink after a certain time an image (most likely going to be what it looks like when your eyes water up a lot) will slowly gain opacity until at 100%. how im thinking i would need to do it is having a a timer and a blink length variable where on a keypress a black image(blink) will be unhidden and rehidden for a second and restart the timer. if the timer hits the blink length (how long the player can go without blinking) the images opacity will go up at a fixed rate. im not sure how I would set this up though, especially the image opacity part any advice?
oh hi @rich adder
didnt you do a timer earlier ?
i did but that was for the monster teleportation, this is a different mechanic
true but the logic is similar
most of these systems are easily repeated but applied in diff context
my main worry is with increasing the image opacity
the opacity thing can also be handled pretty easy,
void SetEyeStrainAlpha(float alpha){
Color c = eyeStrainImage.color;
c.a = alpha;
eyeStrainImage.color = c;
}```
how you map it based on value is up to you , plenty of ways .. Linear, Curve, etc
for sure
if Blink() method is called, reset the timeSinceBlink, SetEyeStrainAlpha(0) etc.
you need two timers or use timer + coroutine
@rich adder do you mind if you explain the opacity thing again, this is what i have so far, ```using Microsoft.Unity.VisualStudio.Editor;
using UnityEngine;
public class BlinkScript : MonoBehaviour
{
public Animator anim;
public float nowTime;
public float MaxBlink = 5.0f;
public Image DarkEyes;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
nowTime += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.E))
anim.SetTrigger("blink");
if(nowTime >= MaxBlink)
{
}
}
}
whats the goal, to animate in and out some ui image?
oh right some thing slowly appears if you dont blink
I would do something like this
float deltaTime = Time.deltaTime;
timeSinceBlink += deltaTime;
if (timeSinceBlink > maxBlinkTime){
float excess = timeSinceBlink - maxBlinkTime;
float alpha = Mathf.Clamp01(excess * opacityIncreaseRate);
SetEyeStrainAlpha(alpha);
}
if (isBlinking){
blinkTimer -= deltaTime;
if (blinkTimer <= 0f)
{
isBlinking = false;
blinkImage.gameObject.SetActive(false);
}
}```
then onyour keypress call StartBlink or something to reset the values and show blink image
how do I fix it, what did I do wrong
you probably want the URP bloom type
you made me realise I haven't download the urp package yet lmao
thanks
my characters xvelocity and yvelocity are all wack and it flips my character wrong
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
Spline Text
is there a way to make sure the physics engine moves a rigidbody an exact amount per fixed update? I'm using ECS physics if it matters
I thought a rigidbody would be moved by its velocity * FixedDeltaTime every fixed update but it doesn't seem to be the case
maybe there's something else wrong though
I have both a collider and trigger (2d) on a bullet object, but when it gets shot it immediately hits the player because self damage is on, how can I make it so that the trigger is off really quickly before turning on
It should yes. Though I don't know much about the ecs physics - maybe it has different behavior. Might want to ask in #1062393052863414313
physics.ignore collision with timer
thank you
healthbar.fillAmount = Mathf.Clamp(currentHealth / maxHealth, 0f, maxHealth);
this isnt working, I think due to current and max health being ints
but like... I have no clue how to fix it
if they are ints then that division can only ever result in an int. you need to cast one of them to float if you want to get a float
I fixed it thank you
I haven't 100% figured it out yet but I think it had something to do with interpolation being on
when I turned it off I started getting expected results with a small margin of error
I do want interpolation to be on, but I want to get the rigidbody's actual position instead of the interpolated position. I'll probably ask around in #1062393052863414313 tomorrow 👍
i am a final year student at a university in VietNam, majoring in game programing , and I have been studying unity for three years. At the moment, i want to improve my English.I'm looking for someone to exchange knowledge with me: i will explain what i know about unity and game programing in return, you can help me improve my English
public EnemyScript[] Enemy;
private IObjectPool<EnemyScript> objectPool;
[SerializeField] private bool collectionCheck = true;
[SerializeField] private int defaultCapacity = 20;
[SerializeField] private int maxSize = 100;
public GameObject BulletStorage;
private void Awake()
{
objectPool = new ObjectPool<EnemyScript>(CreateProjectile, OnGetFromPool,
OnReleaseToPool, OnDestroyPooledObject, collectionCheck, defaultCapacity, maxSize);
}
this is what I have for my pooling script rn, but it cant accept EnemyScript[] bc its an array of scripts and I dont think I actually know how arrays work bc im dumb, please help
Object Pooling is a design pattern that belongs to the creational category. It helps optimize object reuse, which reduces pressure on RAM (used for storage), the CPU (used for logic processing), and the GPU (used for rendering graphics).
However, the main challenge lies in managing object properties: how to make a reused object behave like a brand-new one. If you apply this technique without truly understanding how it works, it is honestly a bad practice.
You should first get comfortable with the basics, such as arrays or lists, by doing simple exercises—for example, creating a list of enemies and spawning them gradually. After you clearly understand how things work, only then should you consider using the Object Pooling pattern.
yeah you're probably right lol
Thanks ChatGPT
Actually, it was my own idea, and I only asked ChatGPT to translate it into English because my English is not very good.
please state when ai is used
answering with ai (even with translation) without specifying is against the rules here
Yes, I will keep that in mind. Thank you for the reminder.
I figured it out I should be able to pool any enemy now
so thats great
is the easiest way to load them all into a pool to just get and then return them
on game load
idk how else I would do it
That sounds great, but there is an important note to keep in mind. When you use this technique, there are two key points you must pay attention to. First, you need to properly reset or adjust the data when the object is being reused. Second, you must clean it up after it has finished being used. This technique becomes extremely complex if the objects you want to reuse have complicated structures and behaviors. This is genuinely based on my experience from a course project I worked on during my second year at university.
yeah I should be able to do that stuff pretty easily I think hopefully
Hey, I want to make a script that involves multiple factors, like deleting a ton of things and resetting the players score to 0 in an endless runner when they collide with things. But all my scripts are monobehaviour and I don't know how to change all these factors at once. Should I combine all of them into a monobehaviour script or do i need to make a new blank script (I did try this once, but I wasn't sure if I needed to do it and quickly became confused with what I was doing)?
all this line of code does is remove any none stackable upgrades from the list after them being used, and this is not the line of code that ois annoying me, it works just fine !
if (randomSO.requiresUnlock)
{
if (!abilitiesOBJ[random].GetComponent<Abilities>().unlocked)
{
return getRandomSO(); <--- this is what bugs me, ha, get it? because it "bugs" me and its a bug? okay I will shut up
}
}
when the code does the "return getRandomSO();" bit, instead of redoing the function again until it finds something that is unlocked, it just returns null
hi, i have an object teleporting (by setting position via script) into a collider with a trigger but the trigger doesnt activate. any way to do this? (2d)
Sync the transform if you're wanting to use physics
You'd want to do so after teleportingcs transform.position = ...; Physics.SyncTransforms();//has some expense
If you're teleporting a lot of objects, do so after teleporting every object.
yo guys i have no expierence with code and i wanna get started with unity. what should i do and if anyone can help me code it will be very appreciated
Check the pinned messages. Unity learn has a lot of free content.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i'd suggest learning c# as a language first, then going into unity and trying it out
(just a suggestion)
doesent unity use C# though
where do i go
or you'd be in a position i am atm trying to make an inventory system with an array and struggling
do i go here
k ty
you can also find tutorials online and/or w3schools website. they're all good for teaching the fundementals of programming
i wish you good luck on your journey
codemonkey and brackeys are good. however, tutorials tends to be mindlessly following instructions and not properly learning in most cases. i'd say reading doccuments and following along and understanding what the code does first before being able to implement it properly
ok im doing unity learn
thank you
@gloomy bison what unity version should i start on I have 2022 but the docs u gave me (unity learn) says to use latest version
use the latest version then
you could just do rigidbody.position = ... instead (iirc any collider you want to move should be done by rigidbody)
(cc @dark hatch ^)
it doesn't particularly matter when you're just starting out, may as well just jump right in with the version you have. unity learn should still have guides written for 2022 anyways, and you'll only really have some UI differences at this stage
does anyone knows a good video to learn how to make an inventory?
i don't think that's possible to be honest. maybe you're getting something that's unity null? how are you checking it's null?
(though yeah you should just make it iterative, go through only the ones that aren't unlocked.)
never mind my code was fine, you know what was the problem? the " if (!abilitiesOBJ[random].GetComponent<Abilities>().unlocked)" line could go from 1 to 11 while I only had 3 abilities 💀 I fixed it and it works great now
let me guess, you were getting an error about null, not null as the result
HI all, New developer here. Hitting 40 im a little late to the game so to speak. Trying to get started as a hobby. I can see quite a few people having this issue around Mouse Look not working. I've exhausted all posibilites and im worried ive just been staring at the answer and missing it. Can anyone help ?
gonna need a bit more context/info to be able to help
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
I really don't know what to do anymore. I can't talk to my NPCs anymore and I always get a "null frenc" response, and I just don't know what to do anymore. I'm totally desperate. I just want my quest to work.
Do you mean that you receive a null reference error? If so, can you post the error along with the script?
mom pleas

o you mean that you receive a null reference error? If so, can you post the error along with the script?
The null reference error is gone.
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
no-one can help if we don't know what you need help with
is bro having a stroke? 
No, I speak German, bro, and my Greek isn't that good.
what's greek got to do with this
tf does greek have to do with this tho 😭
@visual idol do you have a question or issue you need help with or not?
lol
please do not spam, this isn't a social space

Yeah sorry! So, lookInput is not showing as anything, the debug isnt even coming up. I have put other debugs in there so i know the function is hitting.
I do have WASD set up. so im confident my Input Actions are ok.. Not sure what else to look at.
iirc, control schemes are kinda mutually exclusive. that's why the default asset comes with a single Keyboard&Mouse control scheme
you might not need them at all, really
(also for future reference, this would fit better in #🖱️┃input-system)
also, don't multiply mouse delta with delta time, it's already per frame
Hi i downloaded unity recently because i wanted to start creating a video game but i dont know where to start can y'all give me some advice?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
start there ^
I need to json encode/decode dictionaries. Based on my research it seems like I should be using com.unity.nuget.newtonsoft-json. Figured I would check in here before implementing. Any issues with it? System.Text.Json seems like its better but not supported (at least as easily).
it's supposed to be slower than STJ, but it's a bit easier to use, more flexible at times
it's pretty much the standard option
json.net is good reliable choice and is probably already added as a package in your project rn
Ok. Thanks. You guys see, that the package manager has some sort of invalid signature bug happening to all the packages? NBD...they know about/working on it but figured I would mention it.
@grand snow : yep you were right...already installed
Hmmm...would that prevent the package from being available in my project? I'm getting "The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)" even though the package is in my package manager "In Project" list and I can locate it in the Packages folder
If using asm defs you need to reference the one for newtonsoft json
Sorry I don't know what that means....I have the following at the top of my file "
using Newtonsoft.Json;" and then I am using it as "saveData = JsonConvert.DeserializeObject<SaveData>(jsonString);" but it says the error I provided earlier and "The name 'JsonConvert' does not exist in the current context"
Is your ide happy with this code?
If this code is in a assembly definition then you must add the ref yourself.
If not then the automatic Assembly-Csharp asm references everything for you
ide is producing the errors I provided
google is not helping me figure out how to fix this
you have 0 compile errors in unity so it may be working and your ide is lying to you
Save the changes and go check
Hmmm...this is the first time that has happened to me. Ok, let see how it goes
i have a question about raycasting;
my raycast always goes out but:
A. Doesn't show the debug line when I use it
B. Doesn't recognise at least one of my objects.
As shown in the images, they're all on the PickUp layer with the "PickUp" tag.
And as shown in the code block below, this is the code i'm using.
My main problem: The object named "Hammer" does not get registered by the raycast. Am I doing something wrong?
(UNITY VERSION: 6.3 (6000.3.2f1)
// In update function
// Check for player input [E KEY]
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log("REGISTER_E");
// Raycast for object detection
RaycastHit hit;
Vector3 forward = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, forward, out hit, rayDist, objectsLayer))
{
Debug.DrawRay(transform.position, transform.forward);
Debug.Log(hit.collider.name);
// If object, check inventory space
if (hit.collider.CompareTag("PickUp"))
{
for(int i = 0; i < objectsInInventory.Length; i++)
{
// If space, add object. If no space, don't
if (objectsInInventory[i] == null)
{
objectsInInventory[i] = hit.collider.gameObject;
break;
}
}
}
}
}
(what I want the code to do)
I want the code to get the gameobject and stick it in the next available inventory space. Idk if my raycast is wrong.
Any help will be appreciated.
Thank you in advance!
Also, it outputs the names of everything else apart from the Hammer
i take this back. problem fixed; it was referencing the player body and not the camera 🤦♂️
looked this up on google rq
stackoverflow answer: "Actually I solve this problem by adding the modules (Android SDK & NDK Tools, OpenJDK) to my Unity Editor. Actually if you tick the Android build support module, it won't automatically help you to tick the two modules above."
edit: ref - https://stackoverflow.com/questions/61865817/jdk-directory-is-not-set-or-invalid-unity
in the UHUB, go to installs > manage > modules then it should be there
whats wrong there ?
!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/
📃 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's no command called
screensjpts.
No
Be mindful, if someone requests your code as text, don't send a screenshot!
and C# is Case-Sensitive
also you need to configure your IDE
it seems like you have to fix your IDE, you dont have auto code complete
@lunar lotus
Can i not use GetAxis like this? Im getting an error
it is the first time i use visual studio code
what's the error?
also configure your ide
!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
yes and needs to be configured properly, it will also suggest why what you wrote is wrong
where can i turn this on ?
check the stacktrace maybe, it sounds like you're calling it from somewhere you shouldn't
but first, configure your ide
did you save After you updated the code to this
countless times
Doing that rn
i can't find lmao im dumb my bad
You can't find what?
how to turn on auto code complete
You have to follow the instructions in the links sent
if you have issues check here https://unity.huh.how/ide-configuration/visual-studio-code
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
i have this now don't now if its what i had to do
i installed the unity extension and put the external script editor to vsc
you still dont have intellisense working right
try restarting both , Unity and the IDE
did you follow all of the steps in order? it's very important
if you did, then close VSCode and regenerate project files in Unity (in your Preferences menu, go to External Tools, then hit the button)
what did you do 🤔
Hi, how can I fix this?
Wait until Unity releases the fix
thanks
for now just ignore it
Hello, I'm on a fresh project with Unity 6000.3.5f1 to demonstrate an error I've been getting for the past few days.
I merely want to build one of my game projects (built on android,) and I've received the exact same error on every single unity project on Unity 6 as a whole right now.
I've tried anything and everything I could to no avail, and I promise you, whatever you'll ask if I did, I most definitely have tried.
Please help me, what do I do 😭
Looks like some il2cpp generated code cannot compile. are you using the included android SDK or your own?
Everything is the included ones.
Try deleting Library/Bee in your project and start a new build
I've done that multiple times already on multiple different test projects.
Whole Library/ folder too?
May be that you need to re install this editor version or try using android sdk + ndk from android studio
Yeah, whole thing. I've tried to reinstall this editor twice aswell. I've tried to install other sdks and ndks but Unity complains that it either can't find it, or its invalid...when its not.
If done via android studio you have to set the custom path yourself but it will work
just make note of where android studio installs these
I haven't tried directly using Android Studio, that may be a fault? I'll try that now.
It makes it a lot easier to install android sdk tooling
Am I dumb for getting confused with Androids site and downloads? lol
Got it though
hey anyone know why I have this error?
There is a bug listing packages as not safe, i think they are working on it. I believe i saw that on their website
I deleted 65 of projects and hub and application itself Also restarted my licence but never fixed
so is this same for everyone?
@buoyant wasp read this.
and this is a code channel, general Unity questions go in #💻┃unity-talk
I see
does anyone know any app or good tutorial for c# on unity?
thanks!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
☝️ there and see the pinned msgs of this chan
thanks
all the chans on this server have pinned msgs to relevant tuts/ help/ etc
Is this the channel for shader issues
Tried it from Android Studio, no luck, same exact error.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 this doesnt happen on an older 6.3 version it may be a bug you want to report
It happened for me on 6000.3.3f1 aswell
Got enough disk space? no anti virus fuckery?
Over 100 gigs should be freely available, and my antivirus hasn't NOTIFIED me of anything... should I try to disable it?
@NAV
@rich adder
hey
how do you suggest i add a random timer so that after a random amount of time an audio source is played
why ping him
worth a shot
cus he said to ping him if i have any more questions
No luck
this project isnt in onedrive, dropbox, gdrive or similar is it?
how would i use a wait for seconds function but have it wait for a random number between two numbers?
Nope
get a random value in that range, then use that as the wait seconds...
I mean for a specific thing I was helping you on its ok but no need to do it at every question lol
mb lol
plenty of knowledgable people here ready to help out
facts
but yeah the Random class will be your best bet here, Range is the function you'd want
keep in mind If you have a System namespace and UnityEngine in your script the computer going to be confused though to which Random class you want to use because they both have it. You have to tell it either with a fully qualified namespace UnityEngine.Random.Range(etc.. or using Random = UnityEngine.Random at the top
I have it sitting on my 'user' on windows, so its not in any folder of those sort.
The default "personal" folder may use onedrive because microslop are bastards
Your user folder (users/me) is safe
Then im out of ideas 😭
Yeah I tried all kinds of things but
I managed to get it to build yesterday by forcing the missing values inside of the file while it was building, but the app wouldn't open because it was trying to access memory it 'wasn't given permission for'
So, that clearly doesn't work.
And Unity 6 is broken for me as a whole.
I'd use a previous version thats functional, but I specifically need android r27c which unity is very stingy about changing the version you're hooked up to
seg fault? probably due to a null pointer deref from what you tried to make work.
If that file is just missing or empty then its clear something is wrong with the compilation output
The file isn't missing nor empty, it just has 5 values completely not included.
Which you can see here.
{
yield return new WaitForSeconds(Random.Range(1, 3));
Debug.Log("whisper");
source.PlayOneShot(whisper);
}``` im probably being dumb but this isnt playing a noise or running the message in the console
where you call it?
also keep in mind you are using the int version of the Range so its gonna be either 1 or 2 secs exactly, nothing between 1f and 3f , no decimals. The int version is max exclusive so its not going to include 3
in unity 6.2 I think the type includes these
Maybe I can try the LTS for 6.0?
May be better but would require downgrading so ensure you have backups if not using source control
Yeah, I got backups.
Huh, I just tried to build a 2022 project and it errored out with a different error.
Maybe I am just destined to never make games again lol
#💻┃unity-talk
not really a code question
also check the logs and see what they say
I CANTTTT SENDDD A MESSEGE IN THATTTT CHANNEL!!!!!!!
Oh it got fixed nvm
uncs tweaking
guys Im totally new to game dev, whats the easier engine? unity or sbox?
I may be biased but unity
sbox is incomplete and has many unknowns
I think I’ll just try to make a pong in both
I’d like everyone’s opinion. Which of these game concepts do you think would perform better? in terms of player interest and reception.
1. A hardcore tactical fps with small maps like csgo, proximity chat, movement mechanics etc.
2. A survival horror game focused on managing bunker systems and machinery.
3. A story game with PS2-style graphics set in soviet/industrial city.
personally i would like to see 2 or 3, but im biased as im working on a project simular
if your new to game dev the first option definitely seems ambitious
So how do I accomplish this with the new input system?
{
if (Input.GetMouseButtonDown(1))
{
}
}```
An input action with the correct mouse button assigned
or read from the current mouse device with Mouse.current
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.18/api/UnityEngine.InputSystem.Mouse.html#UnityEngine_InputSystem_Mouse_current
Thanks. Mouse.current.rightButton.wasPressedThisFrame was what I was looking for
When you progress past beginner projects or prototyping you want to use input actions
but yea reading from the device directly still works
This is for a temporary menu that, when you right click anywhere while it's open, it closes said menu
Or at least the current instance of it
I have two gamepad-controlled players, but for... whatever reason, they Start() before my two players that are on the keyboard, which causes those to players to attempt to consume the keyboard scheme
I can force the keyboard players back to keyboard, but I don't know of a way to force players into a...
a state in which they are polling for unpaired devices
How to make a flight controller
That's too vague/ simple a question for someone to answer
the simple answer is - write a script
I am making a unity paddle game as my project:
I have coded the lock range of the paddle so it does not go above the screen, but I am having problem the ball being on the middle of the paddle to stay there and move with the paddle as I move it right to left and keep the ball centered and on top of the paddle and move with the paddle as the paddle move right to left. Like the paddle is carrying the ball:
transform.position = new Vector3(Mathf.Clamp(Input.GetAxis("Horizontal") * speed * Time.deltaTime + transform.position.x,-10,10),
transform.position.y,
transform.position.z);
ball.transform.position = new Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime+ball.transform.position.x,
ball.transform.position.y,
ball.transform.position.z);
This is the code. Any help would be greatly appreciate it.
show the full sript
but also - your code is essentially moving both objects with the same code
so it makes sense they move together, no?
both objects are getting Mathf.Clamp(Input.GetAxis("Horizontal") * speed * Time.deltaTime added to their position, identically
When I did this same project (in 2d not 3d) I used Box colliders to stop the paddle and the ball, not the code.
OK
that is the full script
that is in the playercontroller script
So, if I just did one line the type line and deleted the ball.transform..only the paddle moves and the ball fall on the ground. At the start of the game the ball is positioned on top of the paddle.
Yeah of course
So naturally I have to put the script of the ball on the same script as the playercontroller.
what are you actually trying to do here?
those are not the only two options
there is an entire universe of options here
how do you want it to work?
you probably don't want the ball to respect gravity. you probably don't want any of these objects to respect gravity
ok...agreed..the ball should not respect gravity undersood.
also if these objects are physics objects - that is - with colliders, they should not be moving via the Transform at all
@wintry quarry I want when the ball ands on teh paddle it stays on the paddle and when the paddle moves it carries the ball with it
you don't want it to bounce?
of course
You need to have at least two separate states for the ball then - one where it's "stuck" to the paddle, and another where it is moving
but at the beginning of the game it stays on the paddle and once you press space it bounces
"of course" meaning you don't want it to bounce or you do want it to bounce
OK
when you start the game it stuck on the paddle at the beginning of the game
as soon as you press space it bounces on the paddle
OK..no problem , I will work on it. The issue I have is the ball carried by the paddle.
how do I do that?
Make it a child of the paddle
and set any Rigidbody it may have to kinematic
(assuming it has one)
and disable any other movement script it may have
@wintry quarry you said they should not be moving with transform, if they have collider how should they be moving?
Via a Rigidbody
yes
like this?
then I use getcomponent regidbody of the ball?
It worked! So when I press space ....with proper code I can make the ball bounce around, even on the paddle itself?
I cant get my projectile to interact with the ground, even though it set it in the collision matrix
void Update()
{
transform.position += -transform.up * projectileSpeed * Time.deltaTime;
}
private void OnCollisionEnter2D(Collision2D collision)
{
//if (IsRelease) return;
//if (collision.gameObject.TryGetComponent(out JetpackController jetpackController))
//{
// return;
//}
if (collision.gameObject.TryGetComponent(out Ground ground))
{
explosionParticle.Play();
StartCoroutine(ReleaseProjectileToPool(0.5f));
Debug.Log("Hit");
}
}
The Debug message never triggers
fixed , thank you
im trying to fix the movement for moving on this directional gravity circle (like a planet). right now when i try to jump on it, the player only goes up. How do i make it so that the player can jump perpendicular relative to which part of the circle you are on (e.g if you are on the bottom, jumping sends you down.)
Have you confirmed that the raycast hit anything
you'd probably want to raycast to the feet of the player, not down
if you were on the underside of the planet, that'd be casting away from the planet
though actually - that would kinda require already knowing the direction to be able to set the feet in the right direction, wouldn't you want to get a direction vector directly to the planet or something like that?
well cos theres multiple planets. like you would jump from 1 planet's attraction layer to the next.
