#💻┃code-beginner
1 messages · Page 34 of 1
no, your array is in forms of [][], you need to access it through arr[i][j]
ObjectArray[index].Objects[somenidex]
thanks!
i forgot the first array is array of struct
by knowing the background size

Yay, its working
If a background is 10x10 and at position (0,0) is the center of one of the backgrounds then at (0,5) you'd have two background touching each other. From (0,5) up to (0,15) is the second background and so on. Now do the math
Now I dont have to link up my 2d array individually with my game objects.
Can anyone explain in clear language what this is? Main() in c#
Entry point
entry point to the program
but you wont see it in unity
alrightly i will try that in code
To get the actual size of the background in world space look at pixels per unit in your texture import settings. If the background is 10 x 10 px and you have 100 px per unit then in world space your background is 0.1 x 0.1 units
c# is case sensitive
It's simple: Rigidbody exists. RigidBody does not. These are different words. Use the proper names for things
Then keep doing them until that is no longer the case
good luck then
i have no idea how to code that
the idea


If your background is 1x1 unit and (0,0) is the center of the background with (0,0) coords then anything between position (-0,5 , -0.5) up to (0.5 , 0.5) is considered to be within the (0,0) coords
the background on the right with coords (1,0) would have it's center at (1,0) and anything within the range from (0.5 , -0.5) up to (1.5 , 0.5) would be considered to be within the (1,0) coords and so on
On Opening Visual Studio 2022 community version i get this error : StreamJsonRpc.ConnectionLostException:
The JSON-RPC connection with remote party was lost before the request could complete.
i just installed VS with workspace as unity and this happens...
Image
feel free to ping
Basically FloorToInt((camPos + halfGridSize) / gridSize) = coords if I'm correct
If the grid size is 1 like in the example above and camPos is -0.4 on the x axis then you'd have a result of 0.1, resulting in 0
if the camPos is -0.6 on x axis then you'd get a -1 as a result and so on
hard to say from this alone, did you use the Visual Studio Installer.
yes
hmm
Maybe try running visual studio as administrator
Else here's a discussion on it 2 years ago https://learn.microsoft.com/en-us/answers/questions/313193/could-not-start-visual-studio-due-to-an-error-stre
am I missing something obvious? I renamed the variable from m_thrust to thrustMain, and since that change all the force applications just stopped applying
changing the names back did not work the rigidbody just refuses to move
Check the inspector to make sure the values are assigned.
the particle emitters continue to turn on and off so the functions are definitely running
You shouldn't be giving default values to public fields in code, as it's overridden by the inspector.
Are there errors in your console when you run?
An exception in the AddForce call would stop downThrustersOn() from running
I suspect the problem is coming from something else you changed at the same time.
No errors, two warnings but only in the VS console, not the unity one
No errors while running the game either?
Can you share the rest of the script?
and yes, the important part would be while running
Is the rigidbody kinematic or dynamic
yes, no errors while running
isKinematic is unchecked
copying the whole script, what's the tool to make it pastable?
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
your rigidbody doesn't happen to have a mass of a bajillion, does it
if relevant, the issue started happening when I renamed the thrust values, and hooked up the left and right thrusters to the function after I finished tweaking the size and placement
i think the default is just 1
stopped happening?
ah
started happening/stopped working brain bug
mass is 50
but that's intentional and it was working before then
Log thrustMain before you call add force
It'd also show that the code is reaching Add force at all
the thruster particles are working
unless all of the particle systems are incorrectly assigned or something, I guess
I would still go ahead and throw in a log
when you eliminate the impossible, etc. etc.
are you sure you aren't just flying into the floor or something
ship starts the scene in the middle of the space, gravity is lowered so there's a good few seconds in contact with nothing
none of the forces, linerar or torque, apply in that time
your acceleration is going to be very small..
20 force on a 50kg object
i'd just set the force really big and see what happens
okay, probably not that, then
Everything about your code looks like it should work fine.
Did you try by editing the code back when it was public?
If so then that wouldn't change the value
hopefully that meant "tried it just now with 2000"
did you actually recompile after changing the number
yes, both times
tried both
even with administrator
no luck
though humans are fallible yada yada but I'm fairly sure I compiled it
i checked firewall nothings on the block list
Can you screenshot the inspector for the ship?
make sure to catch the entire rigidbody
so when you click Launch ? you get error?
which one are you launching
yes
tried with both
did you try this
#💻┃code-beginner message
particularly about the logs/reinstall
How does it behave when using a huge force value? does it barely accelerate, or does it immediately smash into a wall?
I'm wondering if you had the wrong constraints
Possibly relevant, the gold blocks that represent the thrusters are rigibodies with mass 1 attached with fixed joints
Which object is the joint component on?
lemme see what i can do
the thruster block so when I copied it it maintained the joint and I didn't need to recreate it
I wonder if you were getting a bad interaction between the rigidbodies (through that fixed joint)
I've only used joints a few times before
with a thrust of 200f the ship has a thrust just barely too light to lift it, falls very slowly while thrusting at full
a thrust of 1000f is roughly how it performed before the issue
you said that this happened after setting up the side thrusters. did this involve changing anything about the ship's setup?
I would deactivate those thruster objects see how it's behaving.
had the same thought and just finished test
no change
ship still requires 1000f thrust to mimic 20f from before
that's a factor of 50. are you sure you didn't change anything about how you apply force to the ship?
because a factor of 50 is what you'd get if you switched from AddForce(..., ForceMode.Impulse) to AddForce(...)
the default physics timestep is 0.02, or 50Hz
50 is also the mass of the ship, conveniently
so you also could have previously been adding to the velocity instead of adding a force
or using ForceMode.Acceleration
The only things I did were rename the variables and add the side thruster particle emitters
I renamed the variables by right clicking them at the reclaration and using Visual Studio's "rename" feature
a force of 20 newtons on a 50kg ship would never make it accelerate more than 0.4 m/s
which is very slow. not nearly enough to beat gravity.
the strange thing is, in the first testing
when every rigidbody was the same weight
the thrusters were too heavy and made the handling screwy and bottom-heavy
upping the mass fixed it
and I did have to up the thrust to compensate
but not to this degree
and did you do that by changing m_Thrust in the inspector?
no, I did so in the script
I'm watching and waiting. I want to ask a question but unsure if I should.
just go ahead.
I used the inspector to refine it while running to find the right number, but to make the final change I stopped the simulation and edited the script and restarted it
Editing the script would have had zero effect if it was a serialized field.
The field initializer's value gets clobbered when unity restores all of the serialized fields on the object.
So I was experiencing a wierd bug/mistake before that made things work, and that wierdness stopped working
I feel like you just lost track of your values. Without version control, we can't really confirm what used to be there.
I don't think this is a beginner question but I wanted to ask it here because it's pretty active. I want to edit multiple terrains through script without having a seam like you can in the editor with a brush.
So is there an easy way to do that?
It gathers data from one or more Terrains into a single texture
you can then paint on that texture
I'd like to see an example of how to do this. I've tried it already and I didn't understand it.
I have a (somewhat messy) example from a game I haven't worked on in a bit
I used Graphics.Blit to copy from the source texture to the destination texture. I think I modified a sample shader for that "Terrain Add" material
wait, that's not the right one.
oh, it was. i haven't touched this in a minute 😛
This is all pretty old and messy. I'd rather find something else for you to look at.
I can use the built in shaders though right? For set height or something like that?
Yeah, I bet so
The hidden ones
I was using this to "stamp" the terrain with a texture
It draws on both the splatmap and the heightmap
I just want to modify the height and then smooth it out.
If you want to do multiple modifications, you'll need to "ping pong" between two different render textures
since you can't blit from a texture to itself
Ah, here's a little example.
Note that TerrainTools was in an experimental namespace in older versions of unity
but it should be largely the same
is there a workaround to not being able to use System.Numerics BitOperations
im making a chess engine and my self written GetLSB function is soo much slower than BitOperations.TrailingZeroCount
yeah
replacing my self written GetLSB and GetMSB increased speed by more than 200% 😪
this may be helpful
you'd need to use these inside of Bursted code, I suspect
I think I messed with using these at one point
Looks like I didn't keep any code using them though
appreciate it
I presume that it'd still be faster if you could Burst the mathematics calls
but see how it performs, yeah
I'm fuzzy on what goes on there.
You can burst anything from unity.mathematics
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Yeah, I just dunno what the performance will be like if it's unbursted
Well considering that its bit shifting magic pretty fast
and, vitally, I don't think it's going to be using those x86 intrinsics
but I'm just spitballing
i guess my conclusion is to 
idk what bursting is ill look into that later 🤣
havent even opened unity yet just been working in c# alone
Burst lets Unity compile a subset of C# down to native code
gonna transfer it all later
i see
so do i just burst compile certain parts of code
[BurstCompile] is magic
Hi all, end of a long day and my brain is failing me.
Could someone help me out a little with this little piece of maths? 😦
float hitDistance = hit.distance;
hitDistance = -hitDistance;
dustKickParticleRate = hitDistance * 335f;
Basically I have a raycast pointing straight down, as I hit the 'limit' of the ray I'm setting the particle rate of a vfx graph, what I'm trying to do is invert the distance number so that I can use the distance to drive the amount of particles emitted (lower the further away from the ground).
If that makes any kind of sense. lol.
static methods and anything that isnt a native object can be bursted
so you want to divide by the distance
1 / x is very steep for x values near zero, though
How do I input movement code?
Yeah the distance goes between (roughly) 12 and 6.
6 / distance would give you a value between 1 and 0.5
you could clamp this to keep it reasonable
right okay, well I need to go between 0 and 2000 particles.
you can do a few multiplications and divisions, or just use the lerp methods
Sorry, honesly my brain has really given up on me now, been doing fluid simulations all day. Think I'm a bit math'ed out. lol.
float t = Mathf.InverseLerp(nearDistance, farDistance, hitDistance);
float rate = Mathf.Lerp(maxRate, 0, t);
this would be a linear interpolation instead of 1/x
are you following a tutorial? lots of the stuff on !learn will involve getting movement input
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Yeah, I am, but my main problem is figuring out how to even open the code section.
Is instantiating an object is better or seting it to active and inactive is normaly?
I don't understand what that means.
two different situations
If there's only going to be one copy of something, activating and deactivating it can make a lot of sense
like if there's a door that disappears after you find a key
Instantiation makes sense when you could have a varying number of something
you instantiate a bullet
In general, Instantiating something is going to be heavier than reactivating an old object. However, that old object is going to need to have various values reset in order to re-use, so you need to make sure you're properly setting that
The term for this is "Object Pooling"
If you're going to be instantiating a lot, look at object pooling.
i mean in my case i have a single coin in a single platform so which will be better instantiating or setting it to active
If it's just one thing, probably activating
Yep Thanks All
Hi there, i was wondering how to change a variable in the middle of the same script? For example, i have a variable set to 5, that i want to be reduced by one every second. My main idea is this:
While( timer => 1)
wait(1)
timer = timer - 1
=
hey I'm getting this error and idk where it is in my code can someone point it out (I have no clue ab code)
sounds like you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
By "the code section" I mean the area of Unity where the script for an object would be.
The inspector?
If it says "Miscellaneous Files" in the top left corner, your code editor isn't set up properly.
Maybe idk, it's my first day even with unity on my computer.
It'll be the panel that says "Inspector"
If you have zero idea what's going on, then you should really be following a tutorial.
ah, you are. which one?
Oh I meant the one that looks like this. (Image from tutorial I'm watching)
That's visual studio
After configuring your ide, you may still miss this, because it will be a warning, not an error:
Don't put semicolons after if statements.
This is wrong:
if (something) ;
{
}
This is right:
if (something)
{
}
Oh okay. I'ma watch the video more closely to figure out how they got there.
The tutorial may not explicitly talk about how to install and use a code editor.
Ah it was like this.
how would you go about checking (by script) if an animator controller has a specific blend tree?
This creates a new script asset. It has nothing to do with your code editor.
How do I configure my IDE?
Follow the instructions in the bot message.
AHH thanks
oki
Click the "Visual Studio" link that matches how you installed the editor.
they both take you to the same page, but if you used the Hub, it skips a few steps
Ah ok
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
hi, how can i edit a toogle in the script like how i put a if for
like if the toogle is on that make a thing
sry im french its hard to explain xddd
I configured my IDE and it seems like it's working, I fixed an error
but now I have an warning
Idk what this means ngl I have no idea about code
alright
You have an if statement with nothing in it, and you probably didn't intend to
you have a semicolon after an if statment
nothing within your brackets will run with that there
This if statement has nothing in it. It does nothing at all
ok!
; terminates a statement
Toggle.isOn tells you if the toggle is checked or not
Assuming you are talking about the Unity UI toggle.
yes ty
Are you asking how to check the value of a UI Toggle?
Ah, Fen beat me to it
hey! Im new, can someone answer 1 question?
that would be onValueChanged
ok x) mb, I found an interesting project on the internet that I wanted to explore to understand how it works a bit. I downloaded it as a Unity package, and everything was imported correctly, but the scene remains empty. I just wanted to know if this is normal. 😊
That warning is what I told you earlier
Oh, you were told
The package may include some scene assets.
search t:Scene in the Project window to show all scenes in the project
I'm trying to make it so that when this script is attrached to an object, upon collision it only hurts objects tagged with "Player" but rn it doesn't hurt anything at all. anyone can help? this is like reading another language ngl
yes i make search and find ty have nice day guy
ok I check!! thx a lot @swift crag sorry if my question seems idiot Im learning by myself
Why are you checking if this object is tagged "Player"? Wouldn't it make more sense to check the other object?
YES HOW DO I DO THAT?
that's what I'm trying to do
😭
Call compareTag on the other object
AA how
gameObject.ComparTag() refers to itself, just like using .this in plain c#
if (gameObject.CompareTag("Player")) so I swap compare tag to gameObject?
when using OnTriggerEnter, the local var you create (in this case collisionData) is the refrence to the other object
so if you are trying to check to see if the other object is the player you will want to use that local var, not gameObject
I know very VERY little code I can barely understand
all good, just remember that gameObject is referring to whatever game object the script is attached to
so if you have this script on a cube, calling gameObject will give you a refrence to said cube
so like if (gameObject.collisionData("Player")) is correct?
no
gameObject.CompareTag("Player") is using this object's gameObject property. It is the same as writing this.gameObject.CompareTag("Player"). Collider2D also has a .gameObject just like this does
Use the collider instead of this
no, you dont need to refrence gameObject at all here
I want to attach this script to enemy projectiles and I don't want it to hurt the enemy firing it
what is this
oh
gameObject gives an object of type GameObject.
CompareTag is a method in the gameObject class. CompareTag takes a string as an argument (input).
When you call gameObject.CompareTag(“myString”), it calls this function. It compare’s gameObject’s tag with “myString” and returns true (if they are the same) or false if they are not.
i think you need to slow down and follow some of the introductory scripting tutorials on !learn . you're writing some kinda weird code here
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
I'mma try write in pseudocode
like
if (object colliding with is tagged "player")
{damage that object}
before you write pseudocode, you must learn to actual code
my lecturer helped me with this when I originally did it, but it all got corrupted when my mum used my USB 😭
More like "If the collider I'm hitting's GameObject's Tag is 'Player'"
I have like no time to learn code I need to get this in 😭
YES YES
U had right, there is 4 t:scene! thx, Im trying to open them haha! @swift crag
so this is attached to a projectile, then you want to check if the thing its touching is the player correct?
Then you need to compare the tag "player" to the player object, not the bullet. gameObject.compare is checking the tag of the bullet not the player...
To refrence the object you are colliding with, you use the var you created in OnTriggerEnter(otherobject)
that "otherObject" is anything that enters the collider of the bullet. you want to compare the tag of that
bro, you need to learn. we aren’t here to write code for you
The 's possessive in English is akin to C#'s .
So, you chain those together with . just like you do with 's in English
So, get the collider's gameObject's tag
so this is attached to a projectile, then you want to check if the thing its touching is the player correct?
Correct!
how do I make it so the bullet only activates the subtract health script if the collision is with an object tagged player?
when you use left.right, the program looks in the class of left’s type for a method/field/property named by right
it's so hard to download a project damn
how were you trying to check before?
basically before as long as it collided with something it modified the hp. but I want to make it so only on colliding with the player it does this, bc otherwise the enemy shoots itself when the projectile collider and their own collider merge
yes, I get that but I'm asking how did you try and do it before... Im just trying to get you to think about this a little more in depth. (you were on the right track)
so how would you try and check if the object with a health script is the player?
So, notice how the first line has you calling GetComponent on the collider's gameObject.
Idk 😭 I want it so the modify health part only works if the object is player
So, how might you instead call CompareTag on the collider's gameObject
OHHH
like what digi said, just trying to lead you back to that point; you were 90% correct out of the gate
I know it's just Idk how to write it bc I know nothing about coding 😭
where's the getcomponent part? 😭
its in your sc
all good
OO PFOUND IT
Read the first line of your function
Why did you change the get component
At no point did anyone say that should change
so on that line you are storing the 'HealthSystemAttribute' of whatever object your bullet is colliding with as 'healthScript'. Notice that you get the 'HealthSystemAttribute' from a gameObject... That gameObject is whatever you collided with and its saved as 'colliderData'. using .CompareTag() how would you compare the tag of that colliderData?
I don't knoww :(
You need to realize that code isn't magic. All of the words in each line mean something as much as they do in the sentence you're reading right now
You already know how to call a function on an object
So now you need to call a different component
I don'ttt
I don'ttt
even
yes you do. you've done it repeatedly.
you literally do
The very first line of your code
Is you calling GetComponent<HealthSystemAttribute>() on the collider's gameObject
I didn't write it! I'm trying to modify code from unity playground
But it's in your project
So you can read it
all I'm asking it how to get a working if statement bc I d k syntax.
like
this if statement does nothing
no I want it to compare tag on the object it's colliding with
then you'd better not call CompareTag on gameObject.
ok, then what is the object that you are colliding with?
me! so this is a projectile that should attack me
so the enemy which tracks me fires at me
So then call CompareTag on that object
and this script is attached to the hostile projectile
HOW
the same way you are calling GetComponent on that object
And I've told you how to do that in like ten different ways including pointing to your own code that does it
omg omg omg
I literally can't understand you though
your code already calls a method on the game object you're colliding with.
What is the first line of your collision function
calls a method?
if you have literally no idea what any of these words mean then you really need to just learn properly. !learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
healthScript.ModifyHealth(healthChange);
do I put it in there
No, that's not the first line
What is the first line of the function
I was thrust into the deep end this is my first time working with C# and I'm forced to do this because my existing working scripts my lecturer gave me corrupted
I barely know what a function is in coding
Then go find out
Where's dilly he explained it easier 😭
because if you literally do not know what words mean how are we supposed to help
that is my point. you shouldn't be trying to do this specific task when you don't know what any of the words mean yet.
I know I shouldnt!!! but I'm forced to 😭
this isn't a situation I should or want to be in
So, instead of sitting here repeating that you don't know what things mean, you could instead take that time to go find out
sounds like you need to ask your lecturer for another copy of those files.
There's an intro to C# guide pinned in this channel
It is due in 4 hours
I did he didn't reply
Then you really don't have time to spare
not yet
best get crackin'
no we won't type it for you
not asking you to
just asking you to explain in a way
that's easier for a literal novice
idk whats going on here but ask chatgpt ig
my adhd ass cannot communicate with you
This is a programming discord. Everyone here has ADHD
I cannot focus on what you're saying at all
You know nothing about programming, so it's impossible to explain the solution to you without just giving you working code.
That's the problem.
You need at least a basic grasp of what these things mean
what it means when you see foo.bar.Baz() in a script
Hey I've come pretty far just by interpreting the code I'm attempting to modify
I get it in pseudocode not in C#
comfort wtf is ur og discord tag 
And I've literally just linked to the message where I told you how to translate pseudocode to C#
In english, you would say "Mandy's Wagon". In C# you would say Mandy.Wagon
You have the collider of the object you hit, it's a paremeter to your function
so like compareTag.collider
So, how would you get that collider's gameObject
foo.bar tries to retrieve something named bar from a variable named foo.
That would be getting "compareTag's Collider"
Is that what you want
//how could you use theObjectThatHitMe??
}```
I want to get the bullet to initiate the modifyhealth action upon colliding with an object tagged as "player"
So, you want to check the tag of the Collider's GameObject
You know that the function to check a tag is CompareTag
to check something like that you need to call a method / function
So call that function on the collider's gameObject
yes
yes, and you know how to do "possessives" in C#
collider.gameobject.comparetag("Player")
Okay, now instead of collider use the name you gave it in the function parameter
you know the answer to the question I asked, just read through the statments
Check the code
You're already using the name in several places
including calling GetComponent on it
Or you can look up what a "Function Parameter" is
and see where you did that in your code
no
what does the error say?
That would be checking the tag of the colliderData's gameObject. Is that what you want?
does anyone know how to transfer a project from desktop to a macbook
Why am I getting this error on line 53?
I think so!
You have cropped out the line numbers
Give it a spin and see
oh ahoot i didnt see haha
oh good idea
here, why am i getting error on line 53
IT FLIPPING WOOOOOORKKSSSSS
OnShoot is null. Assuming it's a UnityObject, you can't use the ?. operator on them, they can be "null" without actually being null
It's kind of confusing but don't use those, use an actual == null instead
Seems like it's a custom EventHandler, by the signature
Oh, actually, you're right technically it's all on line 53
So aimGunEndPointtransform could also be null
yea im following this guy
he did that and no error
codemonkey code ?
yeah
ugh why are tutorials teachng to use EventArgs in Unity 😦
codemonkey has bad tuts although he says "its clean code"
Because code monkey
ah yeah codemonkey - that explains it
Action<OnShootEventArgs>, the cleaner alternative since you never actually use the object sender parameter of an EventHandler
If OnShootEventArgs is a class, not a struct, it's still not great
if it's a struct then fine
wait how, im getting error like this
That's not how you write an if statement
hmmm
this piece of code somehow isnt working
thats a big ass chain lol
This is kinda cringe in Unity, just letting you know. it will work fine for the tutorial, but it's a lot of GC for no reason
indeed
yea ig but idk im just following tuto
define "isn't working"
start using the debugger lol
you didn't need to change any of this
You want a != and also where's the rest of your line
you only needed to figure out why aimGunEndPointTransform was null
all you had to do was assign transform
The ?. was completely fine for an event
put the code back how it was
and fix your null reference
Yes, I didn't know what type it was because you didn't show the full code
basically it checks if the enemy is worth more then the current currency available, and if it is less then the room it should start spawning from or more then the room it should stop spawning from and rolls another enemy if so
but now that I look at it
there is 2 conflictions
but in what way was it not working
what was it actually doing
in code it finds that transform by a name
that part is broken. focus on that part
all was working fine but some later enemies were spawning before they should
I bet its using transform.Find
I think its this bc these 2 can never be true at the same time
Now that whole if statement isn't necessary, just get rid of it
yea
my first recommendation is break that ugly line of code into something that a human being can understand
and find out why aimGunEndPointTransform is null
that means the transform you find on, doesn't have child with that name
Drag-drop. Direct reference
basically its a spawner script, the first part is if the enemy costs more then what is available, the second is have we reached the room it should start spawning from, and third is have we reached the room it should not spawn from
but those 2 last ones
are never true at the same time
Yeah regardless of what kind of script it is and what it should be doing, you need to break that line of code into something understandable
maybe this will work
CodeMonkey has the shitcode habit because it's lazy and fast to write. Still shitcode though
how
use intermediate variables
like this?
yes, do it for both
doing Find is ugly af
assign them inside inspector
ok thank will do
preferably start using [SerializeField] private instead of public
var randomEnemy = enemyPool[random];
int enemyRoom = randomEnemy.SpawnableFromRoom;
if (enemyRoom < RoomNumber || enemyRoom > RoomNumber)```
now the if statement is so much easier to read
it's very clear that if (enemyRoom < RoomNumber && enemyRoom > RoomNumber) is impossible
do note that it's quite possible for you to get an infinite loop with this though.
there is actually 1 randomEnemy.SpawnableFromRoom and other randomEnemy.NotSpawnableFromRoom
they are different
i did
Yes it will. Drag in the reference to aimGunEndPointTransform
do i still need this?
and I just figured I shouldve put || in all of them
this is overwriting ur inspector..
i did say get rid of find
ah see - this is what breaking the line of code down does - helps us notice these things
yah you are right, Im always scared if by adding these semi variables
I'll get less performance
Im only using them once
before removing those 2 lines it had an error, now when i removed it, it seems to work...thanks everyone
nope. You have it backwards
Do you intend to make 4,000,000 of these every frame?
doing that whole enemyPool[random].SpawnableFrom thing multiple times is the thing that's slower.
intermediate variables are never worse and are usually better performance wise
think of it this way: the variable exists whether you name it or not.
good to hear thank you
ohhh alright
by naming it you get to reuse them and therefore avoid extra calculations
every time you write enemyPool[random]; it has to call the indexer function on the array
that's not free
it's faster to save it in a variable and reuse that variable. Local variables often don't even have to be written to memory
they can just live in CPU registers, which is the fastest thing possible basically
even if the random changes?
does it update?
or saves to the current random value
no nothing updates
in this image you're using the same random twice though
random isn't changing
hi! currently trying to build our project game.
right now we have a main menu scene and a cutscene scene. when we load the cutscene scene, the entire game freezes for a moment and then nothing happens. no crash. no errors. this only happens with the cutscene scene. nothing visually changes either.
attaching a debugger gives no error message, and neither does player.log. the game otherwise works completely flawlessly in editor mode.
the last message in player.log says: [ALLOC_PROFILER] Peak usage frame count: [32.0 MB-64.0 MB]: 2943 frames Requested Block Size 16.0 MB Peak Block count 3 Peak Allocated memory 33.5 MB Peak Large allocation bytes 0 B [ALLOC_PROFILER_BUCKET] Large Block size 4.0 MB Used Block count 1 Peak Allocated bytes 76.4 KB ##utp:{"type":"MemoryLeaks","version":2,"phase":"Immediate","time":1697574917439,"processId":4928,"allocatedMemory":279875,"memoryLabels":[{"Default":-128},{"Thread":432},{"Manager":9506},{"GfxDevice":72},{"GfxThread":2112},{"Serialization":508},{"String":181},{"HashMap":1536},{"Utility":263624},{"PoolAlloc":112},{"VR":1696},{"Subsystems":96},{"CoreBusinessMetrics":128}]}
but i don't really know if it's relevant.
would appreciate any help i could get :]
do the build settings include the cutscene in the scene list?
when you attach the debugger and pause, you should see what the main thread is doing
i'll try that, thanks
my colliders look weird when the player runs into them constantly
it is, look inside the while
like glitching back and forth
yes but that's inside the while
between the 3 array accesses it's the same
should i change the movement to add force to the rigidbody insead of what it is currently, (Translating)
but I just want the while to stop when the random gets a valid number from inside it
yes if you want collisions to work properly you cannot teleport your object around via the Tansform
alright
I know what you want to do, I'm talking about a performance and readability concern.
yah I'll try implementing it the best I can
for example:
var enemy = enemyPool[random];
while (enemy.EnemyWorth > currentWalletSize || enemy.SpawnableFromRoom < RoomNumber || enemy.NotSpawnableFromRoom > RoomNumber) {
random = Random.Range(0, enemyPool.Length);
enemy = enemyPool[random];
}```
this only does enemyPool[random] once per loop iteration rather than 3 times
AAA that makes sense
is this the right place to look? tried a few times and not getting anything other than this or draw-something
ok I changed it
now I know my while loop is running
cuz its crashing unity
progress
rb.AddForce(transform.right * moveSpeed * movement.x);
i tried this, it worked but the player slides and gets faster and faster
movement.x is horizontal input
does anyone know a workaround in this? im trying to make so the camera follows the player but only in the x axis
@wintry quarry this would be the other thing.
Store the position in a variable, change the X value of that variable, then set the position back to that modified variable
you should see more than one thread 🤔
ok that top one is promising
when you unpause and continue does it stay at that same location?
Or does it switch to other locations?
var pos = transform.position;
pos.x = Player.transform.position.x;
transform.position = pos;```
Thank you
you know you can do this without writing any code though right?
with cinemachine right
im trying to get the camera to follow the player but i dont know how to assign the player to the cam ```cs
public class CameraFollow : MonoBehaviour
{
[SerializeField] private Vector3 offset;
[SerializeField] private float damping;
public Transform target;
private Vector3 vel = Vector3.zero;
private void FixedUpdate()
{
Vector3 targetPosition = target.position + offset;
targetPosition.z = transform.position.z;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref vel, damping);
}
}```
it just stays like that and actually ends up crashing after a while now
doesn't crash without a debugger connected either.
worth noting that the background audio is playing on loop the whole time.
what i'm doing is pressing a button that just loads another scene. that function works fine since other scences load without a hitch. just the cutscene scene that ends up doing nothing.
Cinemachine is the best option but you can also do this very basic thing with a PositionConstraint or ParentConstraint
you would need the script that spawns the player to assign it
would i be able to add a bit of delay though?
public Transform playerPrefab; // assign in the inspector to the prefab
public CameraFollow camScript; // assign in the inspector to the object in the scene
void SpawnPlayer() {
Transform playerInstance = Instantiate(playerPrefab);
camScript.target = playerInstance;
}```
For example^
with cinemachine yes
hmm ill give it another go
Hi sorry I created the particles for the effect of the weapons that string of code I have to inseries to be able to give the input that every time I shoot it starts the effect
Thanks
if (Input.GetButtonDown("Jump") && characterController.isGrounded)
{
characterController.velocity = new Vector3(characterController.velocity.x, jumpHeight, characterController.velocity.z);
}
}
}
the characterController.velocity gives me this, what am i doing wrong?
You can't assign to it.
call Move() to move the controller
Move takes a distance and moves by that much
You are probably looking for Lerp
You're moving by 0.5 meters every frame
That will be very fast
and also framerate-dependent
You should multiply that vector by Time.deltaTime so that you move at 0.5 meters per second, instead of 0.5 meters per frame
that smoothed it out a ton, thanks
How do I fix this?
you need to explain your problem.
i can guess what it is, but i've been wrong before (:
ok so
the spawning is not in the right place idk why
it is spawning way to high or way to low
okay, so i was wrong
i was guessing your problem was that you were going through walls
The position of the object with PipeSpawnScript on it is going to be very important here.
since the script uses transform.position.y to compute where it's going to spawn the pipe
What is this component attached to?
No. The PipeSpawnScript component.
I dont get it (im bad at coding)
You are calculating the offset from the position of the object that has the PipeSpawnScript on it
So if that object is at -10 y ALREADY, that will throw off the offset
also that pivot looks way off
Somewhere in your scene is a PipeSpawnScript.
you attached it to a game object somewhere.
I want to see that object.
press W so we can see some arrow gizmos
might wanna fix this too
that looks reasonable enough
Height Offset is set to 10, though
That looks like it'll be way more than one screen height's worth
Perhaps you need a smaller number.
Change Height Offset to a small number.
See how it looks.
I think your height offset is way too large.
Do this in the inspector.
5?
Show me the inspector for the pipe spawner again.
Okay. It looks pretty even now.
The other problem is that the pipes aren't aligned correctly.
Notice how, in the prefab view, the gap between them isn't at the center?
It's above and to the right of the center.
how do i fix that
notice how the pipes are all at about the same height now. they're just too high on average.
move them.
I don't know what the pipe prefab looks like
Does it have two sprite renderers for the two halves?
If so, move their objects.
surely you have moved objects around before
ah, you deleted the post
Show me the hierarchy window for this prefab.
I need to see every object.
That is not the prefab.
I need to see the hierarchy window while you are editing the pipe prefab.
you have to move the white ones where the circle was. Use move tool you'll see where it is
That is not the hierarchy window.
Double click the Pipe prefab to start editing it.
Screenshot the hierarchy window.
this is the hierarchy window, but you were not editing the Pipe prefab.
That is not the hierarchy window.
Do you not understand what the Hierarchy window is?
nope
It is the window named "Hierarchy". You sent me a screenshot of it a minute ago.
It shows every object in the scene or in the prefab you're currently editing.
Yes.
i have a question.
Move Top Pipe and Bottom Pipe.
i have a project on unity, how do i make it so every time i press "R" the level restarts?
when you click on "Pipe", that will select the prefab's root. That's where the prefab's "center" is.
Move the pipes so that the gap between them is around that center.
If you are using the old input system (which is the default), you just need a component in the scene that does this
wait so what do i do rn
the what
void Update() {
if (Input.GetKeyDown(KeyCode.R)) {
SceneManager.LoadScene("someScene");
}
}
note that SceneManager is in the UnityEngine.SceneManagement namespace. You will need to include using UnityEngine.SceneManagement; at the top of the script.
so what do i do?
Exactly what I said to do. Move "Top Pipe" and "Bottom Pipe" so that the gap between them is at the center of the prefab.
The gap between them is not at the center right now
Click on "Pipe" and look where the arrows appear in the scene view. That's the center of the prefab.
I do not understand what is unclear about this.
Do not move them around in the hierarchy. Move them around in the scene view.
like, change their positions
See the circle?
ye
Move them there...
Press W so that you can see some arrows instead of that tiny circle.
w is not wokring
Click the four-arrow button.
scroll up
That is not right
still didn't click the 4 arrows
you did not click the button. you are still in "Rect Tool" mode
please do what I ask you to
just click it forget W just click it..
I asked you to click on this button.
yes
Click on Pipe. The arrows are the center of the prefab.
did your teacher in school have to show you how to hold a pencil 😆
Click on Top Pipe. Move it so that it's a little above where the arrows were.
Do the same thing with Bottom Pipe.
All of the pipes are appearing way too high because the center of the prefab is not where the gap is.
You need to move the gap to the center of the prefab.
That's because the dot appeared when you were in "Rect Tool" mode.
You switched out of that mode.
Assuming you currently have "Pipe" selected, this is correct.
They will now appear correctly.
the dot is running away from me
what did i say
im trying to come to it
can someone help me?
perhaps clarify whats wrong
What does that even mean? What dot, and what does "running away from me" mean?
AH
See this?
Switch that from "Center" to "Pivot"
Center tries to put the arrows at the "center" of the object
this is often misleading
er, not local
from "center" to "pivot"
my bad
i telled u it was running away from me
BRO IT IS RUNNING AWAY!
whatever the rect tool is doing doesn't really matter
how do i fix this!
so what do i do
ah, I had it stuck on "Center" mode (:
.
do about what
please do what i ask
what mode do i pick
Hi im making a 2d sprite game and added code for an overhead checker, just wondering what to create in the scene to put this in and work
pick "pivot".
done
🙂
now fix the positions of the pipes
you should see that the arrows now no longer between the two pipes.
dont get mad but
the pipe is running away from me
Select "Top Pipe".
What does this even mean
If you select "Pipe", you will be moving the entire prefab around.
do i move one at a time?
You can select both at once if you want to.
Why is so much space being taken up in here with non-code basic beginner stuff
yes, I was just typing that, actually
-> thread
this is not remotely a code problem and we should've moved it a long time ago
@mossy arrow if you have any further questions, please post in #💻┃unity-talk .
"overhead checker"?
Please create a thread in #💻┃unity-talk 😄
but someone said to go here
Doesn't matter.
This is no longer a code problem.
Please make a thread in #💻┃unity-talk .
yes so when im crouching before i stand back up itll check if any obstacles are in the way
ah, right
I would use Physics2D.CheckBox to test if there's anything above the player.
wait, wrong name...
2D and 3D are just different enough to trip you up
This method will check if there is a collider inside the box.
If you set the layer mask to only include the level's layer, then the query will ignore everything that isn't the level.
perhaps...
Collider2D hit = Physics2D.OverlapBox(player.transform.position, Vector2.one * 0.2f, 0, LayerMask.GetMask("Level");
bool canUncrouch = hit != null;
This is probably not the correct point to check, though.
it'll probably be at your feet.
I'd add an empty object to the player where you want the "head check" to be centered at
then just use its position.
Maybe like this.
This is basically identical to a "ground check".
@swift crag Could you check my code please im getting the error Parameter Crouch does not exist after completing my code for the crouch and ive no idea why. thankyou
if you show me your code, perhaps!
whats the website to create a code url sorry?
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class CharacterControllerMovement : MonoBehaviour
{
public Rigidbody rb;
private CharacterController characterController;
private const float YHeight = 1.58f;
public float speed = 650f;
public float jumpHeight = 5f;
void Start()
{
characterController = GetComponent<CharacterController>();
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Get the player's input.
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Create a movement vector based on the player's input.
Vector3 movementVector = new Vector3(horizontalInput, 0, verticalInput);
// Move the GameObject using the Character Controller component.
characterController.SimpleMove(movementVector * Time.deltaTime * speed);
if (Input.GetKeyDown(KeyCode.Space) && characterController.isGrounded)
{
// Debug.Log('jumped');
rb.velocity = new Vector3(0, 10, 0);
}
}
}
can anyone see what i am doing wrong with the jumping part of this script, it doesn't do anything.
I made a daily reward system
You appear to have a CharacterController and a Rigidbody on the same object
Don't.
Smells of gpt
Is this a question
so would it better to do movement through rigidbody or charactercontroller?
this is very weird
There is no "better". Both do some things easier and some things harder than the other
Use a CharacterController if you want to directly control movement.
Use Rigidbody if you want the player to be affected by other physics objects.
sorry for asking a question in a help channnel Fen
Of course, you can also just use a kinematic Rigidbody if you really want.
It's fine to make mistakes. I'm just commenting that it's an unusual setup.
That's not the thing that was called "weird"
it's the attempting to have two different movement controllers
CharacterController is used for non-physical movement. All it does is make sure that you don't go through walls.
rigidbody-light
@swift crag this isnt all the code its just what has been added to make the crouch if you need any thing else just ask
Do you have an animator parameter "Crouch"
ohhhh no i completewly forgot to do that. thankyou sorry i was just being extremely dumb
zap
You won't get a compile error becauase C# has no idea about which animator parameters do and don't exist
As long as you pass a string, it's happy
ok i was asking about it yesterday but this is still bothering me, I have a prefab with a script that has an array on it, when I try to change the size of the array using the inspector, the array disappears completely and I'm getting this wall of text pop up in the console. Nothing sticks out to me as the cause for it to happen, can someone take a look to see if you can figure it out?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i'm randomly getting that too
i have a lot of nested lists in my inspector
what unity version?
I am on 2022.3.10f1 at the moment (the 2022 LTS)
I was on that one, then I updated to 2022.3.11f1 and it's still happening
I mostly just get error spam when any non-transform component is being inspected
in a way that doesn't make stuff actually disappear from the inspector
It was working perfectly fine until I tried to see if I could have nested arrays in the script and that's when it blew up
but I have definitely seen that one a few times..
yeah i've noticed if I click off the prefab and then go back to it, the array is still there and fine
It would just be nice for it to not throw a fit when I want to do it the convenient way
I have had some trouble cross-referencing the error with the code that unity publishes
all of the versions in the changelog are alpha versions
if i try to click on any of the scripts in the error it just comes up with nothing
yeah, because the actual source isn't on your disk
oooooh
what is the difference between behaviors and effective behaviors?
(in ref to: GetBehaviours() & GetStateEffectiveBehaviours() )
https://docs.unity3d.com/ScriptReference/Animations.AnimatorController
It looks like you can override the behaviours that are used by individual states.
notice how you can add behaviours to the layers
not just the individual states
ah, but that's not quite it
You can override behaviours (and motions) for a specific state
I thought entering Playmode reset everything in your program.. like hitting the power switch for a game. I have some stuff that is being stored with don't destroy on load.. and It is persisting.. How the hell do I reset my scene to the default??
So if you overrode the behaviours for a specific state, the "Effective" method would give you the override
not the state's original behaviours
ok, that makes a lot more sense. Not really useful for what I'm trying to do but good to have an answer.
Thanks 😄
(so this was unrelated)
Is there a way to reset everything in your scene within unity? I always thought exiting playmode reset everything to default values and positions. Weird
It generally should, unless you're doing some Bad Stuff
I think instantiating inside OnDestroy is "bad stuff"
I think you'll get a console warning if you do that
Alright.. yeah. That was weird.. it was keeping the xValue I was storing.. even after closing
Can anyone tell me place to go to ask for help with animations in unity?
Were you doing that?
Can anyone help with my crouching, assuming its a coding issue as the speed isnt slowed down when pressing c and the animation doesnt play either, i dont know what you would want to see for help so ive attatched my code below, thanks
use Debug.Log to check if your code is running at all
the running and jumping are all working, just the crouching
Cool. But how do you know your crouching code is even running?
Do this.
its justplaying the debug the entire time not just when pressing c
I don't know what you did, so I can't really tell you anything.
I did notice, though, that crouchPressed is never set anywhere in your code
what can i tell you to help out just to give you a better idea
bruh