#💻┃code-beginner
1 messages · Page 444 of 1
let me give that a try
body.useGravity = false;
even turning off gravity doesn't seem to fix it
i can see the rigidbody's use gravity checkbox gets unticked while im wall running too
maybe show your full script?
is there anything in particular you want to see because the script is really long
dont think i can post it here
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not sure to be honest. seems it shoud proably be mostly ok? The slerp to essentially 0 velocity is a little odd.
what do you mean by that last part
time to add more logs and/or attach the debugger
Vector3 tempGrav = Physics.gravity * 0.01f;```
Followed by
```cs
body.velocity = Vector3.Slerp(wallRunVelocity, tempGrav, wallRunProgress);```
since tempGrav will be practically 0 (unless your gravity is crazy high to start), you're Slerping towards essentially 0
yeah thats the weird part
i turned it way down just to test but the gravity stays the same
i seriously dont get it
wait hold on
you were right before
i changed the slerp to lerp and now the gravity is changing
how tf does that even work
thanks for the suggestion anyway
ah i see
itll probably just be easier to rewrite my code for rigidbodies wouldnt it?
ill do it tomorrow im irritated
each have pros and cons..
All you have to do is add a downward vector into the Move command. That is it. (you are using CharacterController right? Just going on memory)
gravity isn’t hard to do with or without rigidbodies
the main benefit of rigidbodies is that they already have implementation to interact with unity’s whole physics system. To connect with and interact with colliders of different shapes.
And to stage the movements so motion can respect collisions.
The downside is that rigidbodies have several aspects about their implementation that are hard to get around if you need to.
What is wrong with this code? Its "working" but instead of rotating to 50 (the dial starts at 90), it rotates to -39. https://i.imgur.com/aZwkycT.png
transform.rotation is a Quaternion
you're treating it like it's a set of euler angles
you can't do that
because it's not
i.e. plugging transform.rotation.x into Quaternion.Euler(x, y, z) is not valid
you're putting a square peg into a round hole
garbage in, garbage out
so do EulerAngles instead?
no
it's best to avoid reading euler angles back from a transform if at all possible
they're not reliable
what are you trying to accomplish
I'm just trying to rotate towards -40 of the current z value.
I'm not sure what that means exactly. That's not very precise language
I'm trying to rotate towards a certain value. That value will be the current z value - 40.
Perhaps something like:
Quaternion targetRotation = transform.rotation * Quaternion.Euler(0, 0, -40);```
Then later on:
```cs
Dial1.transform.rotation = Quaternion.RotateTowards(Dial1.transform.rotation, targetRotation, Time.deltaTime * speed);```
wow you're still helping out here
i have another question
can i remap materials on a per-instance basis?
@wintry quarry hey, you helped me with my script before, could you also help me figure out why when i stop the wall run coroutine, the player's speed is still super slow and seems like the coroutine is continuing even though it should be stopped? https://hastebin.com/share/sujinutufi.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The only thing that caught my eye is that if you jump from a wallrun, isWallRunning is not reset to false, so the velocities don't get updated in FixedUpdate()
added a bool but that didn't seem to fix it
There might also be a problem when you stop the wall run before the coroutine runs to completion - body.useGravity may still be false
i tried setting use gravity to true separately but that didn't seem to fix it either. I mean its strange because if i stop the coroutine then it should just stop where it is and not even run the part after the while loop
One more thought: I'm not actually sure whether or not a stopped coroutine will pass an equality check for == null... On paper it would still be a non-null value, unless Unity overloads the equality operator like they do for destroyed game objects.
You might test that just to be sure 👀
Yeah exactly:
body.useGravity = true;
isWallRunning = false;```
So these won't run
Which doesn't bode well for the rest of your script
I don't think it will
i added those to the jump call and it still does the same thing :(
you have to explicitly assign it null
im at a loss here i have no idea what im doing wrong
the slide coroutine doesn't have this problem
if you start a slide you can end it whenever you want and you'll have your regular movement speed immediately
What's the current state of your code?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Perhaps the ground check fails immediately after breaking out of the wall run and canWallRun becomes true again, such that the coroutine is started once more.
yeah that seems like it could be an issue
ok so i've added a little check in update
if (isWallRunning && wallContact == null) { StopCoroutine(wallRunRoutine); }
but the issue still persists
Where did that go? I would think to just chuck a Debug.Log() into WallRun() just to check if it's starting multiple times
is wallContact something that's changed externally or some such?
yeah wallcontact is a variable in another script that just checks whether or not the rigidbody is in contact with a wall. I can see it update through the editor and it doesn't react when touching the floor if you're wondering
also i checked the debug log and it seems like when im touching the wall in midair the wallrun coroutine is being called every frame
Excellent - we've located a relevant problem at least 😅
okay so, the sliding is only called once when the coroutine starts and loop runs any amount it needs to, but the wallrun routine is called every frame even when the debug isn't in the while loop
oh my god
thanks so much
the problem was that i forgot to assign a check to wall running like i did with sliding. Sliding has a check to make sure it doesn't get called if isSliding is already true. Wall running didn't have that.
I had just reached that conclusion myself 😁. Solid!
the only other problem i have now is that jumping off the wall doesn't seem to work the way i want it to
it kind of just boosts me forward instead of up
I have these targets in my game that I shoot down and I want to reset them automatically after 5 seconds. I have some of the code but I dont understand how I would go about "saving" the original position. I only have one variable for it but would I need 5 variables as I have 5 targets?
oh wait nvm I think i just figured it out
store the position in a list or dictionary
I would make a custom class to keep it neat
would making an empty at the original position for each target and then using that as the transform be a valid solution?
but ig how you have is good too store it directly on the object itself as V3
creating empty gameobjects still has its allocation ig
why do you need the whole transform?
wdym? like including rotation and stuff?
yeah thought you only want old Position
i dont really know how to store stuff in a list or what even a dictionary is and i also dont know what a custom class is
i think i do want the correct rotation tho fs cause i dont want them keeping their rotation after falling
make it simpler on yourself and store it directly on the object then, Vector3 oldPosition
scale obviously doesnt change tho
then modify it with a method
That might be because after the apex of the wallrun the body may already have some downwards velocity, and since the jump velocity is additive some portion of it would be spent counteracting what's already there. This could have the net effect of slowing the descent or gliding...
But if that's the case, I would think it would behave more as you would like when jumping anywhere prior to the apex
so yeah thats why I suggested a custom class to also keep rotation
ohhhhhhh so i could just add that into my code
i see
yeah thats a good solution
ill try that
custom class is nothing to fret, its just defining how an object would be.
this case you could combine Vector3 and Quaterion
or 2 Vector3s and store as euler
that's a good shout. I tested a bit more and it seems another issue is the wall run is activated again if i try to jump and thats why it looks like im being boosted forward. I'll give it a cooldown and see if that fixes the issue.
okay well my solution almost worked but the only issue is that they kept their original rotationfor some reason
did you store it?
store what? the originalpos in the vector3 like you sad?
I meant storing both as one object
public class PosAndRot
{
public Vector3 Position;
public Quaternion Rotation;
public PosAndRot(Vector3 pos, Quaternion rot)
{
Position = pos;
Rotation = rot;
}
}```
i do not have that in my code no
As an afterthought, you might just set canWallRun to false as soon as the coroutine starts instead of adding a cooldown. That would prevent a second wallrun until the groundcheck clears again
its just an example of what you could potentially do to store both, but ofc you can just store the 2 fields on the object directly
thanks for the advice
really appreciate it
this is also valid
private Vector3 oldPosition;
private Quaternion oldRotation;
public void Awake()
{
oldPosition = transform.position;
oldRotation = transform.rotation ;
}
public void Restore()
{
transform.position = oldPosition;
transform.rotation = oldRotation;
}```
that is what i wrote and when they respawn in the original spot they keep their rotation from when they fell on the ground so 90 off. they also glitch out randomly for a few seconds and then do nothing. when i try and shoot them again they have absolutely no physics
are they physics objects? you want to store the rigidbody.position and also assign it on restore with rb.MovePosition
yeah all physics objects with rigidbody
okay ill make sure to store that and apply that
also is that maybe why they were glitching out. like does unity not like their physics colliders not connected?
no you have to actually reset the velocity
when you teleport you still mainan the old velocity
im guessing this is whats happening , not sure
i think they were fully still but how would i set velocity to 0
rb.velocity = Vector3.zero // linear vel
rb.angularVelocity = Vector3.zero // rotation vel
i put those two lines of code in the IEnumerator and im getting errors
should i put them somewhere else?
What does the error say
"the name rb does not exist in the current context" does it think its supposed to be a variable?
im assuming i did something wrong and was supposed to define it somewhere
Do you have anything named rb in this script?
no
So that would be the problem
oh so do I need to name a transform to some unity function
You can only use variables that have been previously declared
What are you trying to change velocity or angularVelocity on?
anyone got an idea what this means in simpleton words?
thats what i mean do i have to declare like "public (some unity function i dont know) rb"
on the gameObject that the script is applied on
which are targets that are just stretched out cubes
Variables don't use "functions"
GameObjects don't have velocity or angularVelocity
variables have types
variable types yeah sorry
where did you even get the idea to write this code?
this code I mean
the guy helping me before explained that i need to set the rigid body velocity and rotational velocity to 0
ok so you need a reference to the Rigidbody of course
yeah thats what i was trying to do but idk how to reference it
what kind of variable
Okay, so you would probably want to be changing the velocity and angularVelocity of the Rigidbody
The thing you're trying to reference
So, you probably want to make a variable that holds one
What kind of thing are you trying to reference?
gameobject
GameObjects do not have velocity
then rigidbody?
yes
is that a variable type?
of course
how were you using rigidbody this whole time?
All components are
wdym?
you said they were rigidbodies.. i guess they just fall ? you never applied any force to them?
okay so now I would assign the specific target rigid body to that? and that would allow me to set the rigid body velocity to 0 as well as the position to my original position??
wait is it possible that onclick is a variable name in the page and thats whats causing this?
theyre set so theyre standing
i see. so you shoot them and you want them to reset how they were?
i can shoot them and they fall down correctly and after the 5 seconds its told to wait in the code they respawn like this
so you throw a projectile at it not a raycast, thats why they fall down. Gotcha
yes projectile
sorry if i wasnt clear i dont have the knowledge of what is and isnt important and relevant to my code
ok so then just reference the rigidbody thats on the target
and then set it to the original position and rotation as well?
remember this ?
Just replace all the transform with rb.
public Rigidbody Target; i did that at the top of the file is that how I could reference it
this script i s on the target?
yes
okay ill add the other stuff now
and i js changed it ot rb
quick question is this part of the code setting those variables to the position and rotation to whatever they are at the very beginning of the game starting?
yes
and oldRotation is a Transform correct?
no its a quaternion as I wrote it
unity stores rotations in quaternions
they prevent gimbal lock issues
oh im understanding some of the stuff you were saying earlier better now this is making a little more sense
haha yeah it creeps up on ya
More when the object first becomes a part of an active scene... So if you enter playmode and that object is already in your scene hierarchy, it is more or less the start of the game as far as that object is concerned
The code I wrote earlier when I had originalPos as a transform variable is now giving me an error saying that vector3 doesnt have a .position
how would I go about changing the vector3 as a position
that was my attempt
well yeah gameObject doesn't have a Vector3 position
Vector3 position is a struct inside Transform
What you wrote isnt the error that its telling you
Vector3 is the type, a position is a Vector3
Transform holds all 3
Vector3 Position
Quaternion Rotation
Vector3 Scale
you can omit the this.gameObject part
this is still wrong for two things
you want to move the rigidbody position , and assign the variable you had stored
right now you're setting it to world 0 , 0 , 0
yeah i was just doing that as a placeholder
im not understanding these errors but is that how I would want to format tha
Hover over them and you will know what's wrong
The errors are very clear
you made it worse
i literally wrote it for you
oh yeah i see that now im copying it in my b
i just said replace all the ones I wrote with transform with rb. You did something completly different

why is transform.position still there
Seriously, just test your code instead of asking
you dont want to modify the tranform directly with rigidbody
delete the 2 lines transform
i was about to my bad
when i delete the transform.position and just make it position = originalPos; i get an error
mate, delete the whole line not just transform lol
okay ill test now
share the code with the proper formatting instead of screnshot I can show you since this might go on another half hour
lmao im sorry yeah idk how to format that
private IEnumerator ResetPos(Vector3 originalPos)
{
yield return new WaitForSeconds(5);
rb.position = originalPos;
rb.rotation = originalRot;
rb.velocity=Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
}
thats what im about to test
that almost worked. like visually the targets are in the right spot but the bullets just go right through
oh actually it looks like the bullets get affected but the physics are basically gone with the targets like they arent moving at all
how many times is this function called
its in update which looks like once you hit iit, it keeps calling it
you need a better way to start this coroutine
use a Public method which the projectile will call OnCollisionEnter
get rid of that Update
it only calls it if the current position is not equal to the original position and im realizing now i never defined the currentpos
i know what it does, regardless its flawed logic
public void OnCollisionEnter()
{
if(currentPos != originalPos)
{
StartCoroutine(ResetPos(originalPos));
}
}
thats what i have now and i got rid of the void update
noo
do i need to get rid of the if statement
this will call it when the item hits other stuff
OnCollisionEnter goes on the PROJECTILE script
ohhhhh okay
the Target item only has a Public method that Starts the coroutine
public void OnCollisionEnter()
{
}
i added that in the "bullet" script i already ahve which is applied to my bullet prefab
//projectile script
private void OnCollisionEnter(Collision collision)
{
if(collision.collider.TryGetComponent(out ResetTargets target))
{
target.Hit();
}
}
//ResetTargets script
public void Hit()
{
if (restoring) return;
StartCoroutine(ResetPos());
}```
//ResetTargets script
bool restoring;
private IEnumerator ResetPos()
{
restoring = true;
yield return new WaitForSeconds(5);
rb.position = originalPos;
rb.rotation = originalRot;
rb.velocity=Vector3.zero;
rb.angularVelocity = Vector3.zero;
restoring = false;
}```
hope it makes sense where you're not blindly copying it..
i wasnt blindly copying it earlier i swear 🙏 i just dont have a good base knowledge of unity in general
thats why i was having a hard time i think cause i was comparing what you were saying without fully looking at the code
a bit more to do with basics of c#
and all of these snippits should be going in the projectile script?
no..
read the comment above
actually you can even get rid of the Parameter for IEnum thats useless if its a field already. Edited
can someone tell me what this means? i dont have a single variable called "onclick" in all my scripts
open the javascript console
look at the full error
Hey, im currently attempting to create a third person character controller but im facing weird camera/world/player glitch effects (see video) this effect appears either on the player or on the world when im switching the camera (cinemachine free look camera) mode from lateupdate to fixedupdate and vice versa here's the code https://pastebin.com/wizzRc2Z
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.
also did you actually upload a zipped version
am i not supposed to do that
whoopsies
you're supposed to yes
oh ok
making sure index.html is at the root
if(collision.collider.TryGetComponent(out ResetTargets target))
{
target.Hit();
}
i only have an error on "Hit" and its telling me its "inaccessable due to its protection level" and im not sure what that means
i fixed the code. I accidentally wrote Hit as private
these are what are showing up, no idea what they mean
idk afaik this is an error on your webpage/javascript code. Not anything in Unity.
true
i would concur
that worked thank you so much really appreciate the help and especially your time
it doesnt affect the game at all it just does an annoying popup when you start it and i wanna get rid of it, probably gonna have to go to newgrounds forums since this seems like a problem with the website
try making an uncompressed built if you havent already
I don't mean the final zip files.
inside the WebGL settings in unity, compression method. Try without compression
I know github throws a fit when I upload webgl compressed
so I know that it's possible to get the normal of an object using contact points, but how would i get this vector and what is it called? The idea is that when the player collides with an object, the camera forward will determine what direction that line will move in along the object.
Well the line you drew is a seemingly random one, is the player intended to be at the start of that other arrow facing in the direction of the arrow?
If so this would just be vector projection
that would be a tangent vector
and yes - vector projection will get it
project the camera forward vector on the normal
the arrow labeled n is the normal
e.g.
Vector3 tangent = Vector3.ProjectOnPlane(cameraForward, surfaceNormal).normalized;
im afraid i cant understand that
could you dumb it down for me 🙏
n is just the cross product of 2 vectors that lir on the plane, if it's in the downward direction swap the order of the cross product vectors
camera vector is the dark blue
projected vector is the light blue
the surface normal is not pictured, but it would be sticking straight up out of the yellow plane
imagine shining a light straight down on the surface
and your vector casts a shadow
that's what vector projection is
oh ok
so when the camera vector comes in contact with the object, the projected vector only takes into account the direction along the object's surface?
well the vector doesn't "come in contact with" anything
projected vector only takes into account the direction along the object's surface
Yes
ok im starting to understand
if it doesn't come into contact with the object then how does it know a vector is being projected onto it?
just force uncompressed or are there any other settings
nothing knows anything
we just did some math with the vectors
we know because we chose to do the math
none of these things are "aware" of anything, they are mathematical abstractions
nope just try build without compression (in unity)
then zip as normal
if it still gives error then its probably 100% on their end
unless you test it on itch i suppose
yeah i guess that was my bad for wording it that way. I'll try the code you posted before since i kinda understand it now
@wintry quarry thanks so much for that explanation, it works perfectly
i just suddenly found out there's a lot to like about vectors
until you get to quaternians lol
I never appreciated vectors in my physics coursework. I wish I had
They were neat, but not compelling, at the time
Is it fine to have a coroutine running throughout my games entire duration?
Sure
profile it if you have issues
Will do :D
im realising nowadays that a lot of the stuff that seemed boring in school is actually way more interesting than all the stuff that got me hyped up
in the context of school is boring, learning this in the context of a game stimulates the brain more for me
its b/c they teach u the fundamentals.. and leave out the real-world examples
oh definitely, i want to learn way more when its something i care about
not in america
how would you guys recommend I setup a scrollspeed for my timeline, since it'll be based on bpm, I need that time to scroll consistently based on seconds so that my beats line up, it seemed to work fine up until I tried to introduce deltatime
at least not so much inner city schools , teachers are kinda bad
my cousin was raised in decent suburbs they had interesting classes like robotics n shit.
in mine had at most sports..lol
may need to adjust ur values to compensate for the delta
is there a function in unity like ProjectOnPlane but for finding the edge of an object?
we had home-ec and welding / sports
welding at least is useful skil
sports suck when you're a hermit lol
dont think so , maybe you can use bounds or cast on the collider?
https://gamedev.stackexchange.com/questions/126184/unity-detecting-edge-of-mesh-or-end-of-mesh like this?
kind of? I'm not really sure what's going on here. The idea is I want to find the first edge along an direction on an object, and if that edge is within a certain distance of the camera, then that edge can be climbed, like a wall.
u can just raycast forward. and increment the raycast upwards until it misses lol
wdym increment the raycast?
raycast from center.. -> u hit.. okay
raycast from center + 1 upwards -> u hit.. okay
raycast from center + 2 upwards -> u missed..
meaning.. the ledge is between 1 and 2
oh, this just sounds like edge detection in shader programming lmao
yea, but there'd be more too it..
deltatime is the only way it will be consistent 👀
But yeah - as SCG mentioned, since the time of your beats won't line up with your frames very well, you may need to offset the movement in frames that a beat lands in between, based on the difference between when the beat landed and the frame started
u'd have to check if its the same object ur hitting..
u'd have to check if ur within range..
u'd have to check when u miss it is indeed a miss.. and u just didnt shoot thru a gap or something.. etc
interesting
hmm how how would that work? just check to see when the beat object passes over a certain part of the screen?
and then do a bunch of timer stuff to get the intervals logged?
just search for "ledge detection, unity"
now that i know what ur talkin about.. theres tons of examples/ tutorials/ code
run the game.. modify a value (offset) until it matches.. then stop it and hardcode that value into
that sounds super inaccurate for this
ofc, u'd have to watch it for a while b/c just a tiny tiny offset would add up big
lmao
facts
alright, i'll have a look, its usually just tough to find a tutorial that has elements which work with my current setup. I kinda dont have time to rewrite my entire movement script around one mechanic so I'm trying to work with what I can.
im sure theres some math u can do to include the deltaTime..
but im not that math savy, perhaps someone else
thats the case for all tutorials..
u get better at adapting the code..
taking fundamentals u learn.. adapting them to ur own use-case
yeah, i think i'll find something though
thats where alot of ppl go wrong..
they just copy tutorial from cover to cover.. and never really learn anything they're watching
😢 makes me sad
i try not to make that mistake since im aware that just copying does no good
.. it does until u want to change it
good luck mate, come back if u still cant figure it out 🍀
thanks man, will do
uncompressed fixed the typeerror from what ive tested so far thanks a ton
awesome! good to know
its funny because i made the game like january - march of last year but never bothered to fix the issues until now because im trying to get back into the groove of game development so i might as well patch it
it was a fun first project
its always fun to come back to older projects and see progression lol
yeah
unless u forget wtf u were doing
(╯°□°)╯︵ ┻━┻
can u use breakpoints and the debugger to follow the flow of a script?
haha yea its happened before.
gotta write more descriptive comments
they're too descriptive.. and convoluted lmao
i need to learn to do that real quick
basically once you hit breakpoint you can step through
There is nothing exciting about debugging, but it's such a vital tool for any developer. Train your debugging skills now and you'll save an unfathomable amount of hours searching through your code trying to find bugs.
❤️ Become a Tarobro on Patreon: https://www.patreon.com/tarodev
=========
🔔 SUBSCRIBE: https://bit.ly/3eqG1Z6
🗨️ DISCORD: htt...
thankyou, edit: im about to get fool-proof 😅
I want to implement an ammunition system for my special weapon where the game would check from left to right if any of the meters are full, and empty the first full meter the game finds, and fire a rocket. Can anyone help me how I can do that?
i imagine its easier to do in vscomm
The picture is just a mockup btw
well the first full one would always be the 1st one no?
u'd doo all that in code.. (keeping up with values).. the UI would just reflect what ends up from the code
It won't always be
i imagine you would be using them from right to left instead
vscomm always a bit more mature software, vsc one works pretty good too though
Soemtimes the other meters might be full instead of first one, in which case the game would empty one of the other full meters instead
this is excellent.. very str8 forward. thanks
just use a loop/if statements and check them from left to right if its full or not
How do I assign each of the bars?
ideally this would be an array yea
dont focus on "the bars"
this should all be data in code
a array of bars
values* rather
if value = maxvalue (delete dat bich)
else skip to the next one
do you have some type of AmmoBars[] ammoBars
Actually, I haven't done anything apart from that mockup yet. I was asking for a good approach on how I can implement that ammunition system
if u use an image with a fill amount u can just use an Image[] array
0 being the left or right.. -> and just assign them in order
Guess I can make a public array for that
yess
make the data first , so maybe a custom class/struct for what your ammo will be . probably just a simple type of float
or int, depending what kinda weapon you do ig
Should I make separate classes for different kinds of special weapons?
depends whats "different" between them really
no.. u could keep up with all ur weapons in 1 class if u chose
yea this is getting a bit abstract of a question
lol
scriptable objx
I'll start working on the rockets' ammo system now following your advice
yea, if u never done it b4 just focus on 1 ammo type.. (just a value really)
and do the logic/ math and conditionals
then come back
for sure start with the basic one
I have multiple scripts on my player but I only need one active at a time. I need those scripts to be active in a specific order. Only one script in that order should be active at a time. what is the best way to manage that?
with, another script 😂
I was looking into interfaces but I don't think that's quite what I need
huh? you just activate and disable the scripts you need based on whatever conditions you need
surely there's a more efficient way to doing this than having a million "disable everything but this" functions
could call an event
just have 1 that disables them all and then enable only the one you need
thats what i always do.. forloop (disable all) -> enable the one i need
every time
could even have it a method..
DisableAll()
@rocky canyon could you elaborate on how that process works? I'm trying to imagine it in my situation
the process is disable your scripts either in a method or loop or something.
then enable the one you want seperatly
public void EnableGameObject(int index)
{
// Disable all GameObjects
foreach (GameObject go in gameObjects)
{
go.SetActive(false);
}
// Enable the specified GameObject
gameObjects[index].SetActive(true);
}```
but in ur case, u could use w/e component u wanted
.enabled = true / false
You need to be specific with your requirements. Define "efficient" - I'm assuming you're wanting to do less work relative to design (there isn't any class or structure that'll automate this for you if that's your question).
This is pretty much as bare bones in simplicity as it'll get 
I'm trying to make an entity that spawns in every minute or so and hunts down the player. When that entity touches the player, it would flash an image onto screen and play a sound. Could someone help me with that? I'm pretty new to Unity so I don't really know much.
no one will help you with the whole process at once really
do each step one at a time and break it down
Break the problem down and implement one step at a time
how do you spawn an enemy 1st
yeah im not saying for someone to do that
im not actually sure
spawn = instantiate
look it up on the docs and see how to use it
The problem:
- Instantiate (spawn) something
- Delay somehow: timer, coroutine etc
- Player-enemy collision event
- Enable a renderer component or set an object active (flash an image on screen)
- Play sound
The process is that when a counter reaches 5, a new script is enabled and the previous one is disabled. I thought it'd be easier to use some sort of array to keep track of the order of scripts rather than using multiple 'enable component'
correct
you can use an array, still need 1 or a few enable components
u'd not want multiple 'enable components' u'd just need a script to know about all of em and just enable 1 (disable the rest)
Sure, that isn't an issue. You can use whatever collection you'd want for managing the data. You'll need to disable/enable stuff if your intentions is to disable/enable multiple scripts - assuming they're mono behaviour component scripts.
here's what i mean by "spawning an entity"
This is a checkbox
enabling a gameobject
yeah enabling a game object
Yes, that is activating or deactivating a gameobject
ok so just get a reference to it and enable it
how can i make it so after 1 minute an entity activates until it touches the player
well if I've got an array, and each thing is indexed from 0-5 then I'd want to do something like...?
each time the counter reaches 5; enable the next object in the array. Disable all others
Set Active would be the statement used in code
a timer or a coroutine or something
I need to think on this more, but my brain is now spaghetti... This is either a vaguely clever start, or it's very very stupid. I was thinking of something along the lines of this psuedo-code.
Based on beats per second, it keeps track of how long ago the last beat should have occurred - a "beat delta time" - and a method that gets called as close to the previous beat as possible. The bps value could be multiplied to increase the number of beats per... tempo beat, I guess?
My hope is that a frequently resetting timer would be less affected by floating point inaccuracies... Though maybe there's a place in there somewhere to squeeze a little more accuracy out of doubles, if it proves necessary.
It may also benefit from actually checking how far along the audio playback is, if the tracks are not so long as to add more inaccuracies...'
well depends if thats what you wanna do, then yeah do that
since it'll be deactivated u'll need a reference to it.. like said earlier.. to do that for u
that code would run a coroutine like digi mentioned
it's the general idea, yeah
I'm just trying to validate the logic
so basically the entity starts deactivated, after a certain amount of time it actives itself. When it touches the player it would go back to being deactivated and return to its original position. It sounds very simple on paper but I am a noob at C# so I don't really have a grasp on how to code all of that.
for how long private variable will keep its value in editor
You will need a separate object to run the timer, since the object would be deactivated and cannot keep track of time
until u close the program (restart the game)
Context is required
so until i close unity
For the duration of the instance's life.
nah just during the game
editor script
once u restart the game.. or stop it.. it goes back
until you close unity or stop running the game in the editor
If you've got some strange bug occurring, you ought to just explain what's happening.
If you've used an editor script to expose a variable in the inspector, then it will be essentially identical to a normal public or serialized variable
is there any videos to help me learn more about these functions?
Probably
search it up.. you've been told the sequence of events
the best way to learn is just use them your self, the method of using is literally on the documentation
"how to enable disable gameobject in unity"
"how to use a for loop in unity" etc
once u get stuck on something then return with specifics
tutorials should start with foreach for is super unintuitive
nah, pretty common in most languages.. well a forloop anyways
foreach may be special.. idk
They are used for different purposes but can overlap in some areas.
im making a non monobehavior class but id like to use Vector3, should I just make my own struct or is there a way I can import it
- for Loop: Use when you need to know the index or when you need to iterate a specific number of times.
- foreach Loop: Use when you only need to access each element in a collection without modifying the collection's structure.
Did you try just.. using it? Vector3 isnt restricted to monobehaviour
Oh i fgigured that was a possibility. I got to reconfigure my ide lmao
ty
As long as you have using UnityEngine; itll be usable
How do I solve these errors?
You appear to be passing null to a function somewhere.
Okay, will look into it :D
is there a way to make getters and setters for these without writing out entire methods?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Could also just be a unity error, is there a stacktrace
Auto-properties
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
Yeah, but its quite the mumbo jumbo:
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <a26505b064194c429b83f4a02cfddb4d>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <a26505b064194c429b83f4a02cfddb4d>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <a26505b064194c429b83f4a02cfddb4d>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <a26505b064194c429b83f4a02cfddb4d>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <a26505b064194c429b83f4a02cfddb4d>:0)
large code block""
This isn't code, but I understand your request 👍
(Edit: I was replying to weather boy)
Ye unless u did some editor code yourself, just a unity issue
Thanks, I'll look into it 🫡
Not really much to look into tbh, you just simply clear the errors and move on. I vaguely recalling having those errors on some scriptable objects but never remembered why
If it's not going away, then could always try resetting layouts/restarting unity (but that couldve been for another error)
Could also be passing a null to some static function like PlayClipAtPoint
Restarting Unity worked! I have no clue why, but tysm! :D
will including the "set" accessory with a class like Vector3 only allow me to completely change the object and not modify its components individually?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Vector3s are passed by value
The only way to change it is to set it
you can create a class that is passed by value?
or is vector3 a struct
No
But you can make a struct
how do I change this via script?
thanks
The names of the variable in inspector might be related to the names of the variable. You should get used to looking at the docs for stuff like this
That'd make sense, I'll make sure to check that before asking here from now on
Thanks ❤️
So im tryna make it so theres a raycast sent out to the middle of the screen, and thats where the player should be aiming, the problem is that when the raycast from the center of the screen hits a object behind the player, the player looks towards it, subsuquentally breaking their back 💀 so whats a good way to solve this?```Vector2 screenCenter = new Vector2(Screen.width / 2, Screen.height / 2);
Ray ray = Camera.main.ScreenPointToRay(screenCenter);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, aimMask))
{
aimPos.position = Vector3.Lerp(aimPos.position, hit.point, aimSmoothSpeed * Time.deltaTime);
}```
before performing aimPos change, check if hit.point is behind the player
alright let me try that
😮 Whacky - it's never crossed my mind to look into that. I just sort of assumed that that was a detail left up to implementations, for some reason
i'm trying to make a force stronger the larger the distance, but when the distance is less than 1, the force is too small
does someone have an idea of what function/formula to use?
Have you considered an animation curve? It would clamp the max of course, but if there is a maximum defined distance, that is a non-issue
i never thought of that 🤔 thanks! i'll try that now
it worked! thanks so much 😄
Fair enough on all counts!
Maybe having grown up as a dev eating web techs I have just been conditioned to expect less of specs 👀
this is also just how the language presents itself to the user, it doesn't mean that this stuff is implemented with the same language features that it defines.
Ah certainly, that is a reasonable assertion... That was part of my surprise though, that they would bother to supposedly back a struct with an inheritance chain at all, whether functionally or just conceptually.
I reckon it does make a lot more sense in the context of "OOP all the way down." It may have been more of a shock for C being the only other language I've worked in which makes prolific use of a struct keyword; at least to the best of my knowledge. The knee-jerk of what I'm used to thinking of as a central and simple core data type being described with inheritance :)
it would be nice if the type system was cleaner and more "predictable" in that regard, if you think too hard about the low end of the CTS, you quickly run into this confusion and seemingly contradictory features.
probably one of the reasons why some people prefer the more technical languages that force you to do everything yourself.
For whatever reason, JavaScript became one of my favorite languages over the years, all it's warts and weirdness included. It is maybe similar in that capacity - delving beneath the surface can be maddening. I've usually found it best not to look 😅
I do very much enjoy being able to more or less comprehend what my C code is doing along every step of the way without wondering about what's happening to my code within the black box, but I can't say I hold any love for actually working with the language
they each serve their purpose and are best when used within their design goals.
How would I reference another script without using anything from the inspector
thanks
How do i get references from other scripts with my prefabs
Pass it to the instance of the prefab when you instantiate it. It goes over that in the link
look at the sidebar of the page i linked and you'll find instructions for exactly what you can do for that
Ill look into it
Because I can't use GameObject.Find() on inactive GameObjects, I created a static class that stores all UI elements that will at some point need to be referenced.
The UI has some tabs, though currently only the info tab has code set up for switching active UI elements when it's clicked
When the code first runs, it fills a list object that keeps track of all currently active UI elements
The first element is filled out correctly, but the second element isn't and references a null object.
id really avoid GameObject.Find and just make a singleton holding these, that exist in the same scene.
also your !ide doesnt look configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
That's what UI Record is. It's a class that contains a dictionary called "UIElements" that keeps a record of all UI elements that can be addressed by any other script
Why do you think it's not configured
a static dictionary populated using GameObject.Find is not the same as a singleton thats populated from inspector
also you have no coloring on stuff like Monobehaviour which is one giveaway
How do I automatically fill a container object through the inspector
you just drag in the values from inspector, nothing about it is automatic. similar to how nothing here is automatic either since its relying on hardcoded strings
in relation to the error, a null reference error is always the same. something is null and you're trying to use it
Alright, so how do I do that with a Dictionary. It's only letting me me assign GameObjects to Lists through the Inspector
Or should I just create a List and then transfer it over to a dictionary in the Start function
Seems inefficient
Hey all. I'm currently attempting to create a script that enables batteries to spawn in drawers. This script handles the instantiation of both drawers and batteries. The script should only spawn batteries when a drawer has also spawned. However, batteries are spawning when a drawer has not! Could someone help identify what I've done wrong?
The drawer/battery handler script:
https://gdl.space/ohecekubak.cpp
(The drawer spawning system is as follows: Drawer is instantiated alongside its parent prefab, if r = 2, drawer is destroyed)
The battery script:
https://gdl.space/vaqezivubi.cs
(This is here if needed)
I've added an extra collision check to both the drawer and battery, but it still isn't enough!! Help would be awesome! :D
well honestly its questionable as to why you need them as a dictionary in the first place, since you're just looking it up by some string. Couldnt you just declare a field for each ui element?
What was the issue with the input manager?
No because the UI elements are not static, the program will need to create new UI elements dynamically, as well as have functionality for saving/loading them. The reason for using a dictionary is so they can be addressed without having to loop through every single UI element every time a single element needs to be addressed.
there are implementations of a serializeable dictionary online. the other workaround would just be using a list then populating the dictionary yea. this would still be faster than GameObject.Find anyways
The input manager is not bad in anyway, its just simplistic. The input system is highly event oriented and requires far more set-up and configeration. However, its more flexible and versitile, allowing for complex movements. What I'm trying to say is, unless you are planning on complicated and intricate movement/user interactions, then the input manager is completely fine.
Alrighty, I'll do that then
but also your current code seemingly suffers from the same problem
For my project, I'm currently using the input manager- however, I am also not incorperating complex user interaction.
Could you use a site to post your movement script so I could see a possible way to make your movement smoother?
Yeah, the code I showed wasn't the part that created UI elements dynamically, that'd be a separate function, not the Start() function. I implemented the changes based on your input about adding the initial elements through the inspector
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Seems to work
!ide @pliant valley
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
not sure how you're creating them but instantiate also returns a reference to the created object so you could populate it when created. or if you're using the GO ctor then you have the reference right there
screenshot the editor
if it says Misc instead of Csharp -Assembly , its not
close VS, click Regen project files and open script from unity once more
Did that but it still says misc files
I'm going to be completely honest, I myself am stumped. However, I recommend incorperating Mathf.Lerp or Mathf.SmoothDamp. Both of these can be utilized to add a smooth increase in velocity. You know your script best, so incorperate these where velocity or movement is being added. (I am not qualified for this 🤣 )
Here is what I mean:
https://gdl.space/befugehedu.cs
Click regenerate project files while vs is closed
I did. It didn't change anything.
can you show the solution explorer window in VS. If it says missing on assembly right click it and Reimport with dependencies
sweet
Ok a gtag fan game (A popular vr game with hands as movement) Ok, I want to add ropes when you grab them, they move forcefully in the way you push then in, and your hand sticks to the ropes and thier movement, I want this feature to be activated by the grip button
{
Vector2 startPosition = transform.position;
Vector2 direction = (targetPosition - startPosition).normalized;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, 15, layerMask);
Debug.DrawRay(startPosition, direction * 15, Color.red);
if (hit.collider != null)
{
float distance = Mathf.Abs(hit.point.x - transform.position.x);
Debug.Log(distance);
if (distance <= 2f)
{
return;
}
}```
Why do I get 0 distance the first few frames? After the first few frames it correctly sets the distance
You might log which game object the hit collider is attached to... IIRC in 2d a raycast can hit the collider it originates within... though I'm not sure why that problem would resolve after several physics steps
that's what the layermask should prevent and then it wouldn't change the distance after a few frames?
ah fair point 🤔
print something more useful than just a single number. log what is hit, and where
the "and where" part is also important. it seems like maybe these objects are very close to each other for the first few frames
Debug.Log($"{name} detected {hit.collider.name} at {hit.point} from {transform.position} at distance {distance}");
also fun fact, but you don't need to calculate the distance yourself. RaycastHit2D already has a distance property
cool thx
there it is, it's hitting something else
wasn't my mask supposed to prevent that?
have you looked at that object to see what layer it is on?
Never thought I'd need something like this, but it seems insanely convenient. Cheers
Rigidbody movement jittering?
I dont know whats wrong
ignore all the other objects in the hierarchy. They are there to test other things
Here is my camera code
I often forget my pre-processor directives in the heat of battle, I appreciate the followup 🙂
Why is it shaking like that?
Double check your MoveTowards() arguments, and the doc page/example as well, if necessary 👀
I solved it thank you
Harsh but yeah. 
Also, i'm miffed to see get; set; with no access modifiers. Additionally, wrapping over collections is normal. If getting, and adding/setting is the only thing necessary, then that's all that needs to be exposed.
public RectTransform this[int i]
{
get => UIElements[i];
set
{
if (UIElements.ContainsKey(i)) UIElements[i] = value;
else UIElements.Add(i, value);
}
}
hey guys, so me and my friend are making mario and the thing is we are working on two levels on our own laptops.
how do we combine these levels?
we've tried sharing folders (prefabs and scenes) but that didnt work :/
so yea how do we do it?
(we're both beginners
)
lookup version control
Wa.
aight imma look into it!
Thanks!
For scenes, if you're both going to be working on the same scene, you'll need to setup "Smart Merge" for your respective version control.
https://docs.unity3d.com/Manual/SmartMerge.html
By default, one person can work on a scene at a time. They have to commit (save) their changes before the other person works on it, or the conflicts will be essentially unresolvable.
{
SceneManager.LoadScene("MainScene");
InitializePlayer();
}
public void InitializePlayer()
{
level = 1;
experience = 0;
maxHealth = 20;
health = maxHealth;
MinDc = 1;
MaxDc = 4;
transform.position = Vector3.zero;
SetHealthUI();
UpdateLevelUI();
} ``` https://streamable.com/fae5pn When i click my npc and travel to the "skeleton dungeon" and die. The scene comes back to the main scene but my Onclick events are gone and i cannot re-enter the dungeon. I've been trying for 2 days now but im at a wall. Video to show whats happening.
I'm assuming your SceneManager is a singleton?
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}```
Right. So what's happening is you load in, and the SceneManager sets itself in that instance variable. When you change scenes, the SceneManager still sticks around due to DontDestroyOnLoad. When you go back to the original scene, a new SceneManager is created but is instantly destroyed because the singleton is already set. Those buttons have a reference to the NEW SceneManager, which is getting instantly destroyed.
That's why they're displaying "missing".
wow, ive spend ages trying things and it was that simple, thank you ❤️
Can someone help me out here? #✨┃vfx-and-particles message
im sorry for posting here
but im kinda stumped
my unity project keeps deleting itself and i log on to just the main camera and nothing else. This has happened when i have been in safe mode for a couple days. Is that related?
so im guessing the same thing is happening with my playermovement, so ill look into that
Ya it's going to be the same thing.
hmm its getting playermovement from player gameobject, but i need that to be destroyed
or else im running about with a twin
There's many ways to solve this, and managing references for objects that move across screens can be a tricky problem.
But the lowest effort solution is to write a quick script that calls the method on the singleton instance.
{
if (gameObject.name == "Player")
{
if (playerInstance == null)
{
playerInstance = this;
DontDestroyOnLoad(gameObject);
Debug.Log("Object marked as DontDestroyOnLoad: " + gameObject.name);
}
else if (playerInstance != this)
{
Debug.Log("Duplicate object detected and destroyed: " + gameObject.name);
Destroy(gameObject);
}
}
thats attached to my player gameobject
So like for your SceneManager.
public void ChangeSceneOnManager(string levelName)
{
LevelManager.instance.ChangeScene(levelName);
}
put this method on some script
throw it onto the button
have the button call this method
@timber cargo
Getting lost 😛
Do you understand why your buttons are saying "Missing"?
The first button is fixed by removing the singleton from my change scene script. And the same thing is happening to my Player movement script, but it is inside the player gameObject. And since my PLayer game object has a script ^ above that is needed to destroy my player. THe buttons player movement is also destroyed.
Thats what im guessing is happening. And my playermovement script does not have a singleton because it is inside the player gameobject that has the "Dont/destroy" script
The playermovement is attached to the button because i wanted to stop allmovement when the npc was clicked then start moving again when moved to a new scene. It was the only way i could manage to do it
Right so when you come back into the scene, Unity rebuilds everything, including new instances of the Player and SceneManager. The buttons have references to THOSE Player and SceneManager objects, not the old ones currently marked as DontDestroyOnLoad. Then your singleton code activates and kills these copies, so the buttons break.
Makes sense?
Your goal now is to tell the buttons "Hey, don't call the methods on the Player/SceneManager that come with this scene. Call the methods on the Player/SceneManager that are currently stored in those singleton instance fields."
The SceneManager stored here
and the Player you set here
Does this make sense?
Trying to make sense of it but my brain has a monkey playing symbols atm >.<
They're called cymbals 😛
Do you know what a Singleton is?
Like do you know what this really means?
and what you're doing with the whole null check and instance set thing?
Do you know what statics are?
It allows it to be accessed from other scripts
Not exactly. Statics belong to the type itself instead of specific instances of the object. For example imagine if you had a class called Apple.
public class Apple : MonoBehaviour
{
public Color color;
}
Color is not static.
You can spawn multiple apples, and set each to a different color.
In the below case, Color is static, meaning ALL apples you create will share that color.
public class Apple : MonoBehaviour
{
public static Color color;
}
You access static members by writing the class name, and then member name. In the case below, you're setting the value of Apple's color to white. Remember this applies across all apples.
Apple.color = Color.white;
So in the case of your SceneManager singleton, you can write.
SceneManager.instance.ChangeScene(*the name of your scene*);
Thanks you for the help, ill just remove the player movement part until i understand unity and c# more. Getting to lost with this at the moment.
I wanna add a bouncing sound effect to the ball I was working on the other day, whenever the ball touches anything
can I use the original sphere 3d collider as a trigger or is it better if I add a new one instead?
if I add another one I could make it slightly bigger for a more consistent detection idk
not sure if making the original collider a trigger messes with anything since the rigidbody for the physical interaction stuff is already there
how do y'all usually work this kinda situation?
why a trigger? If you already have a physics collider on the ball just add code to it's OnCollisionEnter to play the sound
An rb is not a replacement for a collider. Making the collider a trigger, would prevent your rb from colliding with anything.
okay so I do need to make a new collider that's gonna be a trigger
noted
no, you do not
You don't. Read what Steve said previously
ohh alright I didn't factor in OnCollisionEnter; I thought you could only make scripts do stuff with specific triggers
mb
I'll try to script it with the OnCollisionEnter
it's pretty simple, literally 4 lines of code
I figure
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi im trying to make my character shoot projectiles but i cant get them to go left
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the code is there
and i want to be able to shoot left without changing my players rotation
the bullet is spawned at a gameobject which is a child object of the player
-transform.right
i mean left and right
as in if im facing left
i want to shoot left
and if im facing right i want to face right
shoot right
i am using a single game object for shooting left and right btw
if(left)
//go left
else
//go right```
so get your player to tell your bullet which way to shoot
i have given it a flip function before
That would be the more appropriate solution, yes.
but it would flip the bullet
and when i move it would flip the bullet in the direction i move in
while it is still out
Instead of setting the direction in Start, do it after instantiating the bullet.
as in put it in update?
You'd put it where you'd instantiate the bullet
i have that code on the player
and the code i pasted on the bullet
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i tried to do a flip function but now when i shoot the bullet it only goes right and when i move left so does the bullet
if (facingRight)
{
rb.velocity = transform.right * speed;
}
else
{
rb .velocity = -transform.right * speed;
}
????????????
what did i do
you dont need to set the velocity EVERY frame
so do i put it in fixed update
you do it when the direction changes
isn't that what that is doing
no
and the next frame? and the frame after that?
same thing
so it sets velocity again and again
still don't get it
do you not have 2 if statements which are true when you change direction?
do you want me to put it where i put if input = a or d?
yes, that is the logical place for it
still does the same thhing
yes, that is exactly what you have told it 'to do
ik
Hi, Is there a way to have only one instance of an object when I transfer back and forth between scenes? I added a DDOL on the object on Awake... but when I go back and forth, I have an issue of having multiple same objects
when you have multiple of the same objects its because a new one is created when you go back.
when switching back, check that the object you want to create doesn't already exist.
then you need to implement a singleton patern
or destroy the object when you close the scene 😛
Guys what can be the problem? I'm trying to resize the parallax background to fit to the screen whenever I resize so I can keep the look (This is a map maker for growtopia so I want the parallax to look like growtopia)
And I need to fix this happening when you move the camera upwards
Try debugging the relevant variables/values and see if they are what you expect them to be.
My ortho size goes from 1,25 to 6,5 can that be the reason why it is flickering?
Well, are these expected values?
The kind of flickering that you have in the video would imply that the scale is jumping back and forth.
So start from debugging the scale. Then follow down the calculations path to see where it goes wrong.
Yea my ortho raises 0,25 every time I scroll
Rising every time doesn't sound like jumping back and forth.
This is how it looks like without the resizeBackground void
Ok, so I guess it solves the issue?
How do I make a dropdown menu of everything in my Animator Controller? Here's an image for example
Nope cuz It is not the thing that creates the problem
I don't see the problem in the last gif that you shared though.
Yea but It is not resizing when I zoom out that's the problem on the second one
what are you trying to do?
Only if they are marked as abstract or override
AudioSource is sealed, so cannot have derived classes
force an audiosource to wait until one clip has finished playing until it starts playing a new one, I know I can do it with an extension method, but I was hoping I could override the .Play itself
thanks!
what about extension methods?
What about them?
yes, much easier to create an extension for custom stuff when calling an api method . . .
do they work here?
you can make an extension method for practically anything . . .
Where?
i believe they mean in this — ch3cky's — situation . . .
oh he already said he knows he can do it with an extension method, nevermind
The extension methods can be used regardless of the class being sealed or not
They are the same as normal methods, but act as if they were implemented inside of the original class
oh, i know, haha. @cosmic quail was just wondering . . .
Yeah, I was referring to them, you were the one who's answered to my previous question
they're great for extending functionality of a class . . .
true . . .
i ended up creating a package because i started making a bunch of extension methods. some very specific to me, and others . . . probably not necessary, but for eas-of-use/funsies . . .
damn, that's an entire extension api . . . 👀
no, that's what i need in life . . .
packages that i can import into any package. a core package of common types i use in all projects and an extension package for the same reason . . .
hey all, so I was wondering is it possible to randomly spawn prefabbed tilemaps onto a map? Like a sort of "randomly generated" map? the idea is I want to make a bunch of prebuilt rooms that can possibly be pieced together to form somewhat unique levels
as far as i know u can spawn the prefab tilemaps onto a map
ive seen some one do it before but cant remember the way he did it
alright I def could use some help, this is my second time creating a game in unity and i've been using a couple tutorials, but im realizing my code is all over the place and I'm trying to figure out how to fix it
this is my input manager, which does my player movement
currently im working on the attacking animations
and this is my player controller
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
my issue is that the input manager script is on a seperate object
is your IDE set up? pretty sure it's not, but not familiar enough with VS Code to see
I'm not sure I think it is
but basically the input manager script is on a seperate object, so all I think I need to do is reference the animator attached to my player
but I'm not sure how
can anyone please tell me how to change a game object texture while moving left or right, and change it back to idle when not moving anything. its a 2d game btw
im wondering if I just moved the input manager onto my player object it would be a lot better
there are a million youtube tutorials that explain this
i couldnt find one, do you mind telling me what to search
that's an option as well. it's up to you . . .
This is a two step process:
- Find out how to detect when you're moving
- Find out how to change a texture
Which one do you not know how to do?
i'll look at that one thank you
how to change a texture
https://docs.unity3d.com/ScriptReference/Material-mainTexture.html
Set this to the texture you want
thanks
Heya! Doing an AR project right now and cam across an old problem i already had but I'm too dumb to figure out 😄 I currently have a setup with one parent, 3 child objects and each child has another child with more child objects (yes this sounds very weird haha). Question: I have a script on the child of the parent object. In that script i would like to load the child of the child and unload the other child object of the parent. Is there a way to unload other objects from the same parent? while loading child objects aswell... Not sure if you guys understand my question/setup
xD
(and i know there's an AR channel but this is more of a coding question than AR)
you can enable/disable the gameobject or one of it's components
So I'm gonna access the parent and disable the two other child objects?
sure
and i can acecess the child of the child which i want to load by... doing what?
doing the same thing?
yes? Transform.GetChild, Transform.parent
you also have GameObject.GetComponentInChildren
and Component.GetComponentInParent
sure
this is basically the setup I'm having rn.
So to load the content of the Phoenicians marker, I want to use the GameObject.GetComponentInChildren and activate the content and to unload the other markers i want to use Component.GetComponentInParen?
Ah no wait 🤔
really depends how/what/why you're trying to do this
if you have the parent object, you can just find it's children and enable one then disable the others
if you have the child object, you can find the parent and then disable the other children
Firstly, this is not loading/unloading. This is activating/deactivating.
You can very simply active/deactivate game objects using the .SetActive method
and you can walk through the game object hierarchy using a foreach loop on the tranforms
Wait whats the difference between loading and activating?
your gameobjects in your image are already loaded by the very fact that they are there
I'm having this setup. When i click on either of these orange circles i want to load the content of said area and disable the marker of the other areas, so i doesnt overlap ^^
and yes this is german, no need to read it xD
but i think i know what you mean I'm gonan try
thank you
you could just have some sort of state manager that you call when you click one of these
put references to all 3 in the manager and then there's no need to search for parents and children
you just enable/disable the ones you want
it's easier to help if we actually know what you're trying to do 😛
And trigger each object if the content is clicked
Lmao
Yeah yeah makes sense haha
I'm a bit afraid to show stuff that I'm doing cuz I really hate beeing jugded by people <-<
If there are multiple objects, there may be a need to create a single variable, List, which contains all references to the Buttons, and triggers an event when clicked
private void OnEnable() =>
yourButtons.ForEach(b => b.onClick.AddListener(YourEvent(b)));
YourEvent disables the current button and enables the new one
Is it better to have the Interaction(for example talk, open an specific menu) component in the entity or in the player?
The settings, rules and overall definition of the interaction should be on the object. The actual interaction itself based off those rules, should be done on the player (in my opinion)
could you give me an example please?
A button on the wall?
what should the logic in the player and in the button be?
Player should have button pressing code. It should tell the button that it has been pressed. Then that button should do whatever it needs to after having been told "you have been pressed"
Player is responsible for detecting interactions, and then doing whatever is necessary based on the interaction type (button), such as handling the animation of pressing it
The interaction component on the object can have function calls to sync up its own results locally
OnInteractionBegin
OnInteractionComplete
Etc.
Each interaction type/object will have its own controllers that do what it needs to do. Button opens door. NPC initiates dialogue. Chest drops loot.
so should it be a corroutine?
If you want. Depends on how big of a sequence you want.
So I may have in the Input copmponent that if my player presses "E"...
for example
should I have an interaction component for chests, npcs etc
but i dont want the chests to talk or the npcs to open a box
so it cant be the same component
Hence:
yeah but when I write public void interact{ } how can I distinguish what I am pressing
and, if so, I dont want to make an if, if, if with the components
You can have a base Interaction class, and each controller type extends it
ChestController : Interaction
NPCController : Interaction
(or use interfaces)
I would like to have a common method with different reactions
which do you think is the best way of those two?
You could also rig up a generic interaction target component. Have it invoke an event or UnityEvent or something when the interaction occurs
Oh okay so I have the interface option, the events option and the heritance option
however, I don´t know what is the best way to do it honestly
all of the tutorials I´ve found show this working with events
yeah that's what I do in my current project. just an Interactable component with a few UnityEvents that are invoked when the interactions happen so anything can be interactable without needing to specifically inherit or implement anything. as long as it has public methods (to subscribe in the inspector) i can make it interactable
I haven't implemented one in my current project, but I think I sort of lean that way as well. It could still be extended into another class if it requires some sort of more complex general behavior 🤔
I just checked an old prototype, and that's apparently what I did as well 😆
So events win the game right?
Generic component that then fires events, yes
after implementing it and using it for a while i think i actually prefer this way over the interface/inheritance method because i can move the interaction to another object, like for doors. I can just reuse the exact same door component that opens/closes it even for doors that would be opened/closed from some button rather than directly from the door itself
I seem to have done both, just to force implementing the functions.
Well, time to put that project back to sleep.
Night night, project 👋
the check of interactable area should be in the player or in the object?
Hi, how do I debug a built game? The issue is when I try to "Host Game" or "List Lobbies" that is read from Steam, the buttons don't work. However, when I try it in the editor, it works just fine.
i typically give my player object a component that raycasts to check for interactable objects
Welcome 👋
Check the pins in this channel
same cs if(hit.collider.transform.TryGetComponent(out IInteractable interactable)) { cachedInteractable = hit.collider.gameObject; if(Input.GetKeyDown(interactKey)) { interactable.Interact(); } } but i use Interfaces..
are we talkin about pros and cons?
aight
Yeah but can I attach to a built game?
hint: read the page
Does anyone know how to get rid of the refrence things that keep serperating my code?
that's called code lens. it's typically better to leave it on as it helps with debugging
you mean (1 Reference) thingy in ur IDE?
u can turn it off but i suggest u dont
Why shouldnt I?
b/c its more important than just the refernece thingy
What exactly is it for?
it tells you where you are using the members of your objects. and as long as you've actually got your !IDE configured it is actually useful
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Ok, thank you
are u using vscode or vstudio?
in code u can turn off the reference part seperately while keepin CodeLens enabled
not sure about vstudio
visual studio
ahh, sorry
it can be turned off in studio as well, up under options
w/o disabling the entire codelens plugin?
Via VS Code settings: Go to File > Preferences > Settings and search for "csharp.referencesCodeLens.enabled" and make sure its unchecked. code allows u to disable just the references
Question, I'm trying to make a moving system like skyrim or portal, but instead of the object following the players mouse, it stays on the ground, and moves with a delay, basically like real life. How would i go by doing this?
like this but 3D?
Yes but its in 3d space, and i dont want it to leave the ground much or at all.
hmm.. let me think about that a min
i use spring code btw..
w/ strength, dampening, etc
ok
u can probably raycast towards the ground as u do it.. and when it gets too far away stop it from lifting anymore
Okay, or i could freeze its y?
u could.. yes
ok
depending on how it looks.. u probably need to try a few different methods
Yea i will.
how to check if the moving player has crossed a certain boundary?
(i need to write a code where the player can't pass a horizontal/vertical boundary)
i wanna limit the player's movement area to just the red lines and the vertical blue line in this image
Use a collider
Yes now use more colliders to make the boundaries
those colliders will be applied to a separate sprite ye?
yup, raycasting off teh ground and lockin the y pos works
may want to work w/ rotations as well
Okay thanks.
Should the interactable area be a child object or is it better to have it in the player gameobject