#💻┃code-beginner
1 messages · Page 12 of 1
I really don't know haha.
I thought the naming thing had to do with ECS where you may want a bunch of related components in one file (since they often only have one value per struct).
But that doesn't explain monobehaviours which I'm probably wrong about anyway
Ecs components are not MonoBehaviour though, so they wouldn't need to change it for them to be stacked in one file.🤔
No yeah, that's why I said I was probably wrong about it hahaha. That part is just about the file name matching the class/struct name
Didn't read till the end...👍
can I somehow use convert an enum to an int easily? (basically use the 0-4 numbers without usign a switch or something similiar)?
just cast it to an int . . .
My smooth camera follow makes my game lag a bit. How can I fix this issue?
By providing more context around the issue, like relevant code
(int)myInt / myInt as int casts it into the number it represents, assuming your enum inherits from an integer.
(string)myString / myString as string casts it into the string representation you defined the enum under.
If you plan on passing a number rather than an enum, I advice you use Enum.IsDefined or something similar before anything else.
so what exactly are am i suppose to use then
Delay the call ?
how do you do that in edit mode?
You may use this, not sure it will work but it is worth trying https://docs.unity3d.com/ScriptReference/EditorApplication-delayCall.html
thanks
anyway i can make a solid block that can only move when being pushed by certain tagged objects and acts as a solid walls for others using rigidbody?
My Map moves slightly upwards and i don't know why
If the animation of the parent is playing, then the animation of the child object is not played. I want to make the character stand up in a pose, and the weapon shoots, with its own animation. An animator has added an animator to the weapon, the trigger is triggered and the states are switched.
can someone help me? this is on the Item script and its supposed to stack items, and it kind of works, but it removes both of the items since its on both scripts ```cs
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.GetComponent<Item>())
{
Item collisionItem = collision.gameObject.GetComponent<Item>();
if(collisionItem.itemData.maxStack > 1 && itemData == collisionItem.itemData)
{
Debug.Log("Items can stack");
int totalAmount = amount + collisionItem.amount;
if(totalAmount <= itemData.maxStack)
{
Debug.Log("Stacking items");
amount = totalAmount;
Destroy(collisionItem.gameObject);
}
}
}
}```
how else would i do it
I'm making a pixel simulation and thus made a pixel data class, now I want to make this into a grid and my first thought was a 2d array but I'm wondering if anyone has any ideas that would work better?
wouldn't it be simple to just instantiate a new GO "Stack" with the info of item amount in it ? Your items would both disappear and a stack would appear
trueeeee
the stack would be stackable as well but adding the correct number of items into the final stack
Destroy doesnt happen till end of frame is the problem here
(feel like I'm using "stack" a lot)
Sounds fine to me
also how should I go about displaying this array?
loops?
wondering if I want UI with horizontal and vertical layout groups or simply squares spaced apart
wouldnt be too hard to make it in 3d space
wouldn't it cause rendering issues?
ok I'll try that, thanks :D
got any other ideas?
get Y position of items that collide, Destroy higher object and add stack information to lower one
add collisions
Could just make a member bool isStacking and tick it when one executes
there are no race conditions, so you'll have info when one or the other executes
it's just destroying doesn't work until end of frame, so even after being 'destroyed' it'll still run the logic
something like this?
im so lost
i dont understand whats wrong, it always make grounded tag true, and when i try to make it false in inspector it sets true, but i does not touch any object
it works when like when i stack to the max stack size
Ok, so the way I'm thinking of the logic is they collide, you check if the component you collided with is a similar item.
Now, if the component isn't being stacked, then you run the code and then flip isStacking to true. So, now the other item will run the same code and fail when it check's the other item isStacking
...
Your IDE* has a little green line there giving you a clue that might help
if (grounded = true)
{
animator.SetBool("IsJumpingDown", false);
animator.SetBool("IsJumpingUp", false);
}
i removed it and it fixed
is it making tag true? how?
when using the = operator, you're assigning something usually
but you're not trying to assigning anything here, rather you want to compare
which is the == operator
okay, it helped, thanks
always check the hints your ide gives you
Hello, I'm trying to override Cinemachine input manually.
Documentation said:
Cinemachine has defined an interface: Cinemachine.AxisState.IInputAxisProvider. If a MonoBehaviour implementing this interface is added to a Virtual Camera or FreeLook, then it will be queried for input instead of the standard input system.
But how exactly am I supposed to do that?
I tried to make script and add it as a component:
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CinemachineManualInput : AxisState.IInputAxisProvider
{
}
It's not correct... what is the correct way?
ah right thank. It didn't hint me toward that earlier because I didn't add MonoBehavior before AxisState.IInputAxisProvider
A quick question, how should I code a side view camera movement where upon touching a certain position in the scene the camera will gradually advance forward, such as in an automatic scrolling level design or going through a doorway?
I think theres a couple of ways to do that.
From the top of my head: Have a trigger depending on a specific number before it starts to move on its own , or you could use a collider for when it triggers / deactivates
So : Bool for when the camera follows the player and when its off - auto progress forward
Can U help me I have this error: NullReferenceException: Object reference not set to an instance of an object
AnswerButtons.Start () (at Assets/Scipts/AnswerButtons.cs:43)
and this: NullReferenceException: Object reference not set to an instance of an object
AnswerButtons.Update () (at Assets/Scipts/AnswerButtons.cs:49)
Whatever you're using on these lines is not assigned (null)
Basically read the error message
Yeah, sure, but whatever you're doing in that script is not set to an instance of object
may I send code?
Send it
!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.
line 43 has a reference variable that is null
line 49 has a referebce variable that is null
check the value of any reference variables on those lines and make sure a value is assigned to it . . .
it is longer but I make it short
how are you gonna use the bot command then completely ignore it
lol
There's no Text component most likely on these GameObjects
You can also just reference the component instead in the inspector
not the GameObject
100% the issue is that they are using TMP_Text objects in the scene and not UI.Text objects
You should not reference things via GameObject, it's a waste of time and leads to runtime errors like these
yea this is it the turtorial I copy it was older
yeah so take the advice the others gave and reference the components directly instead of referencing the GameObjects then using GetComponent. but also use the correct type
thanks all
make TakeDamage public
when no access modifier is specified, it defaults to private
o thanks dude
What does "{ get; set;}" in Unity mean?
Same thing it means in C#
not a Unity thing, it's a C# thing
Should go through the scripting courses pinned to this channel if you do not know
Thanks
It's the first topic in the immediate scripting course
one is the subtraction compound assignment operator. the other is the regular assignment operator with a negative sign after it
=- means you forgot to add a space. It's valid, but i =- 1 is the same as i = -1
-= (one operator) and = - (two)
Huh okay
Spaces aren't mandatory
this also leads to funny things like 3 !>= 5
this returns false
it's actually parsed as 3! >= 5, where ! is the unary null-forgiving operator
(only relevant if you told the compiler to error any time you use a variable that might be null)
my animation wont play on my cinemachine i have it set to increase my fov in the animation and it plays through script and its not working
it keeps saying defualt clip could not be found in animations list
📃 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.
{
isSat = true;
anim.Play();
}```
sounds like you're trying to use the (extremely) legacy Animation component
You should use an Animator.
why cant i use the legacy system
well, you can, but it's very old and barely used anymore
you'll have a hard time getting help on a deprecated design (component) . . .
I have a 2D game and for a certain reason I need the camera to be attached to the player as a child. Is it possible to have camera damping while the camera is a child of the player?
Sure, but Cinemachine would make that really easy
just track the player and give the cinemachine camera some damping
hey peeps, whats the best way to set a variable on a script on an instantiated object, from a separate, other script, thats instantiating said object. do I have to make a function for this in the instantiated object (lets call it "setProjectileDamage"), or is there an easier way?
is damage() a method or a variable?
take out the () and it should work if damage is a public var
make sure prefab is of the type you're trying to interact with , eg your "other script"
Hello! Is it possible if i want to make movement for 2 different players in a single script
yes
its an INT variable in the script of the new instantiated object
you can call a method with a parameter that assigns the variable you want to change, or if the variable is public, you can access it manually to assign its value . . .
you could lets say use an enum to distinguish between player 1 / player 2 on the same script then set it to be different on each player
How would I do if I want to generate and shuffle a deck the same for all connected clients, using netcode? I already have the working functions for generating deck and shuffling it.
NetworkList
also #archived-networking
sorry didn't see that channel, also thanks
i've given this a go but its still throwing up an error message
display error message . . .
what is the error?
i dont mind using a function within the instantiated objects own script to set the variable (which is public!!) but i'm struggling to understand why I cant set it from the other instantiating script
you have to change the prefab type to the script you want to access, like i mentioned here #💻┃code-beginner message
it cannot be GameObject
GameObject does not have a member named damage. It never will.
the type returned by Instantiate is the type you gave it. if your prefab variable is a GameObject, then you'll get a GameObject back
it'll be a game object with your projectile component on it, sure
the instantiated object returned is a GameObject type. you need to access the component on the GameObject . . .
im trying to work my head around how do i make this work
change the type of the prefab to instantiate the type you want to access . . .
you can reference a prefab as a GameObject, or as any component on the prefab
Instantiating a component instantiates the entire object the component is attached to.
Prefabs references should almost never be a GameObject.
You want something more specific than literally any game object, right?
A GameObject is a container holding a list of components; its prime use is activation and deactivation. Primarily, we need a specific component attached to the GameObject. Change the type of the variable (field) to the component (you want to access) instead; this avoids using GetComponent whenever we grab an item from the object pool . . .
this is a lot and i'm lost now
it sounds like using a method on the new objects script would be easier?
show the code where you declared your prefab (the one you instantiate) . . .
either option: calling a method, or assign the variable manually is only a single line . . .
https://hastebin.com/share/koqokuyehe.csharp heres the whole script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
your prefab variable is a GameObject. a GameObject does not have the damage variable you're trying to access. does that make sense?
yeah, i can understand that
what script has that variable?
this, which is attached to the prefab being instantiated
then you need to use that script as the Type of the prefab variable instead of GameObject . . .
So you should have a variable of type CrescentDartProjectile and drag in your prefab
now, when you call Instantiate it will create a copy of the GameObject, but return a reference to the CrescentDartProjectile script, allowing you to access its public members . . .
so change the "GameObject" into "Type" ?
No.
.
^
that's all
no, Type in this context is the class you want access to, your CrescentDartProjectile . . .
I don't know what this has to do with anything we're saying
They mean in the code
you are showing us random screenshots instead of doing this..
ok so i've gotten rid of the line that said public GameObject prefab and replaced it with " public CrescentDartProjectile prefab;//new
"
if i'm understanding this right, this should now work as intended?
wow, that worked, thank you all for your help.
right so my player is riding a cart and when they jump off it i want the momentum from the cart to be conserved onto the player how would i do this
if the player is riding on the cart don't they already have that momentum?
Baically it's going to boil down to how your player movement works generally and how the "riding the cart" mechanic works
How is the player "riding" the cart?
its attached to the seat and the cart gets translated
the short answer is "when the player leaves the cart, give it the same velocity the cart had"
the cart doesnt have a rigid body tho
So there is no momentum or velocity involved. If you want physics-like movement, you should probably use physics
but you know the velocity, because you're moving it.
im translating it tho
so?
You're translating it by the amount equal to the velocity you want to impart to the player
how can i get all the colliders that overlap another collider?
2D? 3D?
2d
thats true well i could modify the movement speed when it jumps off the cart then change it as they hit the floor but if they jump off and dont press any buttons they wouldnt move at all tho
Didn't you write it ?
i dont know if i did it correctly
Then test it and see if you get satisfying results
what does the perlin noise look like in unity
i mean to say that if it is like the one on the left or right?
Yes.
(The joke being that these are both perlin noises with different parameters)
It's just a question of scale here i think
As digiholic say, you can obtain both result IIRC
I'm struggling with my bullets. They work fine if I am going straight ahead but since my ship continues on it's velocity when turned if I shoot the bullets don't take the ships velocity. I was thinking of using Vector2.Dot(xx,xx) but I'm not sure what the solution is. I want them to adopt the moving direction velocity. :/
Relevant Code: https://gdl.space/bicilesevi.cs
Here's a good tutorial: https://youtu.be/bG0uEXV6aHQ?si=CGDr-CJ30-Ayak8E&t=542
I linked to the relevant part where you change the scale and the image looks like the left or the right in your examples.
Let's have a look at Perlin Noise in Unity.
More on procedural generation:
● Sebastian Lague: http://bit.ly/2qR3Y3P
● Catlike Coding: http://bit.ly/11pMR7O
♥ Support my videos on Patreon: http://patreon.com/brackeys/
····················································································
♥ Donate: http://brackeys.com/donate/
♥ S...
It will depend entirely on the scale you sample the noise at
Mathf.PerlinNoise(x, y) samples the noise at coordinates [x,y]
suppose you plug in positions in your world
you'll sample 0,0 at the origin, 1,0 one meter to the right, etc.
now, instead of plugging in the position, plug in the position divded by 10
now you're sampling 0 , 0 at the origin and 0.1 , 0 at one meter to the right
oh
This stretches the noise out by a factor of 10.
not an expert but..such a weird way to move
Vector3 pos = transform.position; Vector2 velocity = new Vector2(0, (bulletSpeed + playerSpeed.magnitude) * Time.deltaTime); pos += transform.rotation * velocity; transform.position = pos;
is it possible to test for a collision between two objects when neither of them have a rigid body
a seed is put in (like minecraft) and the actual number is generated from GetHashCode()
no, collisions is physics
then i just use a random and get a random number from that seed
then we plug that in when getting values
If you make the numbers that go into PerlinNoise larger, then the noise will change more rapidly
If you make them smaller, then the noise will change more slowly
it changes by 1
Should I scrap it and rethink the approach?
You can use physics casting if you don't want to use rigidbody to check for colliders
Just set the initial velocity of the bullet to be equal to the ship velocity
if the seed is 10, then it starts at (10, 10) then goes to (10, 11) then goes to (10, 12)
note that adding an enormous random number doesn't really make sense
did you mean to add a random value between 0 and 1?
System.Random.Next is a random integer
yeah why would the bullet not just be
rb.velocity = transform.right * speed; (assuming your object default points Red arrow)
or w/e
thats to make it different everytime
Also why are you recalculating the velocity every frame? @radiant vector
good point. Calculate one time, then move it the same amount every frame.
oh, I see, it's constant
gotcha
I would still use smaller numbers. You're going to run into problems with floating point precision with huge numbers.
Let me try something like this. I know I tried it but I forget why it didn't work.
Maybe just add a random value between 0 and 10000 or something
anyway, multiply x and y by a scale factor to change how big the noise is
so id shoot a raycast to test instead?
yeah if the mapwidth and mapheight are 10, then it takes 100 values from a random point on this infinite perlin noise
but its for the purpose of, if u want to always have the same world, then u can always enter the same seed
also, that reminds me
then assign the direction
as long as you spawn the bullet with the ships rotation
var bulletInstance = Instantiate(bulletPrefab, firepoint.position, ship.transform.rotation) etc..
I believe perlin noise is 0 at integral coordinates
what does integral coordinates mean
coordinates where every number is an integer
[3,0]
hm, it's not zero, but it's certainly the same value every time
I tried Debug.Log(Mathf.PerlinNoise(Time.frameCount, 0))
It's always 0.4652731
so i have to use floats
So, you should definitely be rescaling these coordinates
or multiply it by something
I would suggest doing this
float sampleX = x * scaleFactor;
float sampleY = y * scaleFactor;
Mathf.PerlinNoise(sampleX, sampleY);
where scaleFactor is a float
well, it probably won't be changing
wait why dont i just add 0.5f to it?
but making it const will stop you from editing it in the inspector
that helps, but you might as well add scaling here too
this is on a static non monobehaviour script anyways
i have a very rudimentary question
if i want to fade in/fade out a canvas
is it better to use an animation system or modify the alpha/opacity value of an image directly from code
I just do it in code.
Animation makes sense when you can't easily express the animation in code.
for example, animating a character's limbs
yeah thats what i was wondering
I do this all the time
canvasGroup.alpha = Mathf.MoveTowards(canvasGroup.alpha, shown ? 1 : 0, Time.deltaTime);
shown is a bool
canvasGroup is a CanvasGroup
thank you im going to try it out now
Hello I created this function however after adding the foreach statement it tells me not all code paths return a value
public string UpdateObjectiveProgress()
{
foreach (var quest in questList.Quests)
{
if (quest.Base.RequiredItem != null)
{
var inventory = Inventory.GetInventory();
int itemCount = inventory.GetItemCount(quest.Base.RequiredItem);
return $"Obtain {quest.Base.RequiredItem} ({itemCount}/{quest.Base.RequiredCount})";
}
else
return quest.Base.ObjectiveText;
}
}
What should it return if questList.Quests is empty
Hello, I'm looking for a way to create grid lines similar to Debug.DrawLine? Any suggestions? currently looking at either using LineRenderer (which will require handling many line renderers) or instantiating gameobjects per grid box
Nothing
So, you'll need to tell it that
I tried just else return but thats not correct
Put a return statement after the foreach loop
Im unsure how best to do that because if I return an empty string that im not going to set to anything wont I get a null reference error?
you MUST return a string
an empty string is a valid string
a null reference is also, according to the type system, a valid option
probably not what you want
Strings can't be null. Your function will return a string in every case, or it won't compile. That's why you have to tell it what string you want to return if the list is empty
It wasn't the string itself I was worried about it was where I use it but I realised im being stupid and can just check where I call the function if questList.quests.Count > 0
||Update: upon further review, strings can be null in C#. Still probably shouldn't return null though||
strings are just immutable; they aren't value types
What do you mean by immutable?
You can't modify a string in-place
so with an array, you can do
arr[3] = 123;
you can't do that to a string
obviously you can reassign the variable entirely
If I return null would that anger you?
but that's not modifying the contents of the variable
It might anger the compiler
well, if you try to display that string, you'll have a bad time
an empty string sounds fine, as does "No active quest"
Yeah I see the issue but the case for this string is the string thats never going to be used
So im assuming I can just return an empty string and not worry about it?
Sure.
If this is an unusal situation that should never happen, you could throw a Debug.LogWarning in there
I do that in places that shouldn't ever be reached
Ok good Idea I will do that then!
Thankyou both
Um help, a = b, why are the saying first number is equal to second, I don't understand...?
== means "Are these equal?"
a == b is asking a question. It returns true if a equals b.
If they are not the same, it will return false
= is the assignment operator; == is the equality operator
== is in the same family as > < >= <=. It's indeed comparing two things and giving back a result
Ohh, wait, I got it.
Thanks!

I still kind of don't understand though, I mean "a" is not equal to "b"
but also they are not greater than 10
so if they are greater than 10 but not same, it'll return false.
That does appear to be what this lesson is trying to convey
&& means "and"
but if the answer is greater than 10 and it is not same, it will also return false?
Yeah I know about this, thanks.
if their sum is greater than 10 and the first two are equal, do the first block. In literally any other case, do the second
Ohh, yeah damn, I got it, thank you so much and sorry.
uh why my browser crashed??
hey is there anyway to make ur raycasts visible to check stuff
; ends a statement. A while loop applies to the next statement.
So you're doing nothing as long as counter < 10 is true
Debug has something
Debug.Ray?
Notice the squiggle here. The compiler is warning you about this
ill try that thanks
Debug.DrawRay
Just looked it up
https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
Oh, so it kept like repeating the loop that made my browser crash?
thank u
your browser freezes until it's done running, so yeah
Got it, thanks.
{
Debug.Log("woking");
sitCheck();
pm.isSeated = false;
}```
my ray cast isnt working
and im not sure why
Try using Debug.DrawRay to visualize the raycast
so, Debug.DrawRay(gameObject.transform.position, cylinder.transform.up, Color.green, 1f);
that'll draw a green line that lasts for 1 second
just a little tip - the == true part is never needed and is just extra noise
if is already checking for true
anyway "doesn't work" doesn't mean too much to us. Perhaps if you explained what you are expecting this to do and what it's doing instead?
i have no idea what its doing cause when i draw the raycast out in debug i cant see it at all and i want it shooting out from the front of a gameobject and if it hits a game object marked with layer "ground" for it to be true
why can't i put my CharacterController component into the Character Controller reference?
i customized it a little bit it works nicely ty
Does your script name match your class name
Your own script is called CharacterController, so you can only drag-drop yourself on it. Change the script name
ty!
But also do make sure they match
Oh that's funny -- the original CC icon still shows up
Yeah last compilation pass failed, that's why
already did it, they didn't match
fixed it
Where are you casting the ray? It's in update, right? The ray only lasts a frame, so you have to keep calling it
If you can't see the ray, then you're either shooting it from the completely wrong place, or you're not shooting it at all
Post the whole script via pastebin.com or similiar
Hey guys, just a quick q (might be an easy fix but new to unity thx) my models clothes n hair etc is glitching through any idea how to fix?
probably not a code question
oh yea sorry!
im setting a bool fron another script true in a different script and im getting the object refrence not set to an instance of an object error does anyone know a fix
Why everything I have learned feels like I understood nothing bruh
you are not getting a good reference to the other script. Do you check?
Reference an object instead of not doing that
make sure the reference object is not null before attempting to access it . . .
well its set to false before so i dont know why it would be null
wdym
the bool is not a null, the reference to the object holding it is
You should probably just share the code at this point
Your error says you're trying to get something from a reference that doesn't exist. Instead of doing that, try using an object that exists instead.
Post your code via pastebin
the object reference can be destroyed before you access it again to change the bool variable on it . . .
{
Debug.Log("woking");
pad.GetComponent<BoxCollider>().enabled = false;
StartCoroutine("colliderCooldown");
sitCheckFalse();
playerm.isSeated = false;
}``` its the last bool statement which is the issue
its not being destroyed
playerm is null
how
How do you reference playerm?
¯_(ツ)_/¯
You haven't showed us anything related to how you're getting the reference
We can't know with only that snippet
PlayerMovement playerm;
You should share the whole script with a paste site
is this variable assigned from the inspector or through code?
That is a declaration. It doesn't mean it's referenced
that is a declaration. there is no assignment here . . .
Well, not ONLY. You also have to reference it
You could also do it other ways, but public allows you to do it in the inspector (also another way, but I won't add more confusion)
quick question: how do you assign the number 5 to an int variable?
Paste the whole script via pastebin
(variable name) = 5;
right. did you do the same thing with the playerm variable? did you assign it to a value?
its not a variable its a class
Ffs
That you have as a variable. The class is the TYPE of that variable
Collider is also a class. But you use those as variables, right?
PlayerMovement playerm;
int health;
no, playerm is a variable of the type PlayerMovement, just like health is a variable of the type int . . .
Okay so where do you set it
its fixed now u guys gotta chill lol
a class is a Type, moreso, a reference type . . .
Everyone is "chill". We're trying to help you...
But sure, insult us lol
Like 5 people asked you to post the script
chill, we're just trying to help? 🤔
I'm not chill but that's just sort of a state of being for me, I'm always highly caffeinated and anxious
Unrelated to the current situation
I'm using the Modular First Person Controller from the asset store to control a bumper for a pool game type thing, to allow the player to steer around a bumper. I glued a cube to the player and applied a super bouncy physics material, but whenever the ball impacts the bumper it loses all velocity. The physics material is working on the walls of the play space, all velocity is correctly retained.
Does the ball bounce correctly when it hits something else?
that's what I'd look at first
yes, the walls of the play space are made of a cube with the same physics material and it behaves as expected
a pool game type thing
is the ball hitting the bumper, or is the bumper flying into the ball?
all velocity towards the player is lost, but any sideways skew is retained
the ball essentially stops dead and begins drifting to whichever side it already had sideways velocity in
either one, whether the player is actively ramming the ball or the ball is flying into a stationary player
the properties of the two bodies, if relevant
and the scene heirarchy
the chaos balls are set to be given a 50 velocity kick on game start and have their y level locked to 2 with no gravity, so they skim the ground without drag or gravity and bounce infinitely
Is there some way to fix A polygon of Mesh ..... in Assets/Prefabs/Office.fbx is self-intersecting and has been discarded.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
your model has a weird polygon in it
how would I fix it
like a quad shaped like this
you could go look at the model in Blender and try to find the bad polygon
or just ignore it
hmm, how should I like, make it work
the fbx looks horrible
that's very vague.
missing a lot of textures and all
(this is also not a code problem)
half of the textures
oh yeah
you can ask in #🔀┃art-asset-workflow . I'm guessing you need to go manually assign some textures.
Just did a test and can confirm the behavior also functions when two balls collide
Check if the rigidbody is sleeping after it contacts the bad box
how can I check that? pause and framy-by-frame or do I need a script?
In the script, debug log therb.isSleeping()
should i put that in update or oncollision?
On collision
enter or exit?
Both technically, but I'f it's sticking it might not be exiting
returning false on both wall and player collisions
configure your !IDE so you don't make spelling mistakes like that in the future
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
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.
yes, your code editor should be flagging the error for you
both functions are returning true, as well. Checked, both Enter and Exit are running
Damn. I got nothing then. Whats the box that's not working look like. Is it intersecting another collider?
there's a capsule on the back that's part of the player controller, could that be causing it?
Move the box a little bit further away.
hey there, this is my item script, and the OnCollisionEnter destroys both items when stacking them together
https://hastebin.skyra.pw/kucufawatu.csharp
And off the floor a lil
its because the script is on both items
thats why it destroys them both
but i dont know a way around it
I guess they both destroy themselves cause they both run that method lol
When is sleep true?
typo, sleep is always false
Oh ok
make one of them special somehow maybe lifetime in the world whoever is newer it gets destroyed for older one
Adjusted positions, no effect
Might need to move to physics channel
ok
Does it matter which one I press
yes
select the one you actually plan to use
and make sure its the one that has Unity Workload installed :p
idk the difference
Both have unity workload installed
I also have this if it matters
Idk which one to use either
shit's confusing
well one is a preview version. surely you didn't just randomly install that for no reason and actually planned to use it for something? or did you just go and install each free version?
I'd use the third one since it's the stable release. Second one has nothing to do with Unity, and as the description says, it installs the tools required to make software without VS installed
yup old way of getting VScode to work with unity back in the day was using the Build Tools 
any way i can get the geometry of, say, this tree with Physics.OverlapSphere? it doesn't have a collider
you need collider
it doesn't have a collider
then it will not be detected using a physics query like Physics.OverlapSphere
I have no idea honestly it was a long time ago
what do you mean by "get the geometry" exactly? The Mesh it's using for its MeshFilter/Renderer defines its geometry.
So I should use the Visual Studio Community 2022 one?
yes
Yes
yeah, I'd like to be able to check if there is a mesh at a specific position for an effect
give it a collider
it doesn't need to be perfect. Looks like a CapsuleCollider will be a decent approximation in this case
ayo ur making that horror game?
Can I uninstall the other two?
yes
im making that horror game
ill live to see it being made on like 20 platforms
if you don't need collisions for it that match perfectly to its mesh, just use a primitive collider like a capsule or box collider.
(what horror game are we referring to)
idk I forgor
i forgor 💀
yeaa
this is not lidar game dw :)
Basically it's a sound-based horror game where your footsteps reveal the environment :)
DareDevil - the game
now i just gotta figure out how to apply a mesh collider to this model i imported.
Add Component > MeshCollider
because ' ' is for char
" " for strings
oh so ' is for one character and " is for words, right?
pretty much
for strings, not necessarily words, but a string of chars . . .
Got it.
if I use the input action on the keyboard "any key" can I print out what key am I pressing?
Are you talking about this? https://docs.unity3d.com/ScriptReference/Input-anyKey.html
no
im talking about the new input system
with callback context
can i print out from the callback context which key im pressing?
Uh what am I wrong doing now?
you are missing some operators?
You just have d e with nothing between?
and a * b <what goes here??> (c + ..
Oh bruh, got it, thanks.
yeah unlike when writing the text as a math expression on paper or something where the multiplication operator can be implied, in programming the operators are required
can someone help me make the OnCollisionEnter so that it doesnt destroy both items?
https://hastebin.skyra.pw/usefizalih.csharp
Is this script on both objects
yeah on all items
private void OnCollisionEnter(Collision collision)
{
if (gameObject.GetInstanceID() < collision.gameObject.GetInstanceID()) return;
// the rest.
what does that do?
Clever
it makes sure one of the objects runs the code and the other doesn't
The instance ID is effectively a random number assigned to each object. One of them will be less than the other, and that one gets to live
like this?
or have i got the wrong idea
!cdisc
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
it works
but
sometimes when i drop like you can see it gets stacked to the item on the floor, but sometimes the floor item gets stacked to the item which still has velocity
how could i make it so that it always gets stacked to the item on the floor?
if you have some particular criteria you want to use to determine which item is destroyed and which isn't, go ahead and use that. The one I provided is merely guaranteed to pick one of them, but makes no promises about which
If you want to do "destroy the one at a higher y position", that should be simple enough to do
basically the same technique as the code I shared, just checking a slightly different thing.
imo implement lifetime like I said im assuming you will want to despawn very old items later on as well it will double as factor which item runs its code
maybe the one which has less velocity?
when im splitting items in my inventory i instantiate new ones
if you can dream it, you can write the code for it
so that wouldnt work
thats why when i split the item, and then throw it out it gets stacked to the floor item
and when i throw the original item without splitting the one on the floot gets stacked to the one you threw out
no like imagine your on ground item has lifetime of 40 seconds since it got dropped and your new dropped item has only half of a second since it just started existing in world then you can compare and stack to the older one, solving your current problem + use that lifetime to despawn old items to not clutter
what u do in ui dont matter its only ui representation of ur item not like an entity in the world
yeah but when i split items in the inventory
into half
i instantiate a new item
wouldnt that matter?
is ui item class same as the item you drop into the world?
why u do that
wdym
u dont need items to exist in world to have them in inventory
yeah ik, but when you drop them they wont appear from air
so i do need them to exist
because when i drop an item out of inventory
all i got to do left is set it active
and add force
visually they still appear from air
Your inventory slots should probably always exist and you just change what sprite and number they display based on what item is in that slot
anyways u need to change ur whole inventory setup for my thing to work so forget it 
thats what i do
yeah to check which one has less momentum is the best option
probably
yeah im lost, it doesnt work```cs
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.GetComponent<Item>())
{
Item collisionItem = collision.gameObject.GetComponent<Item>();
if(collisionItem.itemData.maxStack > 1 && itemData == collisionItem.itemData)
{
float thisMomentum = GetComponent<Rigidbody>().mass * GetComponent<Rigidbody>().velocity.magnitude;
float collisionMomentum = collisionItem.GetComponent<Rigidbody>().mass * collisionItem.GetComponent<Rigidbody>().velocity.magnitude;
int totalAmount = amount + collisionItem.amount;
if(totalAmount <= itemData.maxStack)
{
if(thisMomentum > collisionMomentum)
{
collisionItem.amount = totalAmount;
collisionItem.GetComponent<Rigidbody>().mass += GetComponent<Rigidbody>().mass;
Destroy(gameObject);
}
else
{
amount = totalAmount;
GetComponent<Rigidbody>().mass += collisionItem.GetComponent<Rigidbody>().mass;
Destroy(collisionItem.gameObject);
}
}
}
}
}```
you should be doing something like my previous code was doing
check if you are the faster or slower object
if you're the faster object, jsut return
the other object will run its code and destroy you
yeah i tried and its giving me errors
when the item touches ground
https://hatebin.com/qgqgofanes try this
or anything
you naturally need to check if the object HAS a rigidbody before using the Rigidbody
TryGetComponent would be useful
also avoid using GetComponent so much - cache the reference
you can also probably just throw that in as the first line inside the if (collision.gameObject.GetComponent<Item>()) block
and it should be fine too
guys, why is my instantiate not working? I made this condition and even if I set it as true by default, the particle is not generated void Update { if (isInFire) { Instantiate(fireParticles, transform.position, Quaternion.identity, transform); var v = fireParticles.GetComponent<DestroyInRandomTime>(); if (!v.isActiveAndEnabled) { hitsReceived = maximalHitsToDestroy; } } }
isInFire is likely false
You can verify with Debug.Log
And if it's true, you're getting stuff on the prefab
Not the instance you created in the scene
if you just did
public bool isInFire = true;``` that's not going to affect any already serialized components in the scene.
You need to actually set it in the inspector
even if i set the bool in true it happen anyway
oh,thanks
show how you did so
because you probably didn't do it properly
var clone = Instantiate(prefab, ...);
var p = clone.GetComponent<T>();
// use 'clone' and 'p'
how come the rotate on the camera returns back to its original after the turn of the mouse variable changes at all? (lines 9-10 and 25-27)
^
{
public GameObject toiletSherds;
public GameObject explosionParticlesPrefab;
public int minimunHitsToDestroy = 6;
public int maximalHitsToDestroy = 12;
public int hitsReceived;
public float impactForceScale = 1.0f;
public float velocityOfImpactForExplode = 7f;
public float velocityOfCollisionByObject = 4f;
public bool isInFire = false;
public GameObject fireParticles;
public int random;
public float maxDetectionDistance = 10;
public float maxDetectionForce = 5;
[System.Obsolete]
private void Start()
{
random = Random.RandomRange(minimunHitsToDestroy, maximalHitsToDestroy);
}
void Update()
{
if (hitsReceived >= random)
{
Instantiate(explosionParticlesPrefab, gameObject.transform.position, Quaternion.identity);
Destroy(gameObject);
Vector3 position = gameObject.transform.position;
Quaternion rotation = gameObject.transform.rotation;
GameObject sherds = Instantiate(toiletSherds, position, rotation);
}
if (isInFire)
{
Instantiate(fireParticles, transform.position, Quaternion.identity, transform);
var v = fireParticles.GetComponent<DestroyInRandomTime>();
if (!v.isActiveAndEnabled)
{
hitsReceived = maximalHitsToDestroy;
}
}
}
}
Somehow Start is marked as obsolete lol
right so like I said public bool isInFire = false; if you just changed this to true that's not enough, you need to set it in the inspector
in theory this should work now```cs
private void OnCollisionEnter(Collision collision)
{
//If the collision is even an item
if(collision.gameObject.GetComponent<Item>())
{
//If you are the slower item
if(gameObject.GetComponent<Rigidbody>().velocity.magnitude < collision.gameObject.GetComponent<Rigidbody>().velocity.magnitude)
{
Item collisionItem = collision.gameObject.GetComponent<Item>();
//If this item is even stackable and is the same as this item
if(itemData.maxStack > 1 && itemData == collisionItem.itemData)
{
int totalAmount = amount + collisionItem.amount;
//If the total amount of both items can fit into the max stack size
if(totalAmount <= itemData.maxStack)
{
amount = totalAmount;
Destroy(collisionItem.gameObject);
}
}
}
}
}```
right?
we use Begin(); now
oh ok i will try
void Begin() {
pinMode(1, OUTPUT);
}
because if i not put that,the random var returns me a warning
Yeah you should be using Random.Range()
It's RandomRange() that's obsolete, the warning should be telling you that
Oh my god that's adorable
Unbelievable
Let me guess, the namespace System and the namespace UnityEngine both have a class called Random
does awake get called when an object is instantiated?
Yes
it gets called during the Instantiate call in fact. By the time Instantiate returns, Awake and OnEnable will have already run on the newly created object (assuming it starts out enabled)
also anyone knows how to simulate the fire in barrels like gmod?
Particles, probably
the fire is semi transparent,and it is in a position in the middle of the object which if the rotation of the object changes the rotation of the fire will not be affected either
Yep particles
Just make sure the particles are simulated in world space (setting to change) and you'll be fine
oka
wait, to make the particle not rotate relative to its parent object, do you use Quaternion.Identity?
Mmmm that thing is familiar to me
it works now
Thanks for your patience
i would recommend against calling get component in any method that gets called beyond Start unless it only runs once
it runs once
Drop only runs once ever?
It should run every time you drop an item, right? In that case it may be better for item to simply have a reference to its own rigidbody.
what is going on why my draggable rect transform isnt at 1:1 sensitivity https://hatebin.com/viqsujtofv you can see mouse moving centimeter on screen but star image which is child of "StarsRoot"(the thing which is dragged) moves like 3 apparently scale can mess it up but my whole hierarchy is at scale 1 so what else
That's a double transform
why double?
I've never experienced it in unity. I've only had it happen in Maya when the parent transform is += to the child transform because of history
Not sure if that helps or not
As a hack I've fixed it with extra empty parent
Don't know if that works in unity though.
yea idk I shuffled around everything anchors setting position or local position instead of anchoredPosition remade canvas altogether
Are you using a script to link their positions?
that sensitivity isnt even same when mouse approaches edge of screen it accelerates too im so confused
im changing position of empty element with just rect transform according to how mouse moved
https://pastebin.com/h0W7BRJh this is full class it goes on ui element which gets dragged around might be a bit messy as its thinking code not actual implementation just started this thing
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
thing is at the morning when I did that it worked as I wanted I dont know when it started this bs it just did
say I have a script attached to a prefab and like 40 copies of the prefab in a variety of scenes, and I want something to affect all copies of that prefab. Can I just make a static method in that script and then call that static method elsewhere and it'll be called on all copies?
I feel like it won't work on unloaded scene copies
Your calling in update.. multiply your mouse input by Time.deltaTime
hello, I am currently trying to activate the children of my parent object through a script in the parent object. I figured out how to reference a variable from an entirely different script but now I am struggling with figuring out how to activate each of the children based on the value of the variable from the other script. How do I go about this?
i really dont know how to setup my code architecture for editor stuff -_- theres no simple way for monobehaviours to subscribe to editor events in edit mode
Never multiply mouse input by deltaTime.
Mouse input is the amount of movement since the last frame
Dang Brackey! His curse will never leave us! lmao
ig im going to sleep with this big unsolved
aint no way bruh
always the 2 + 2 = 5 bugs
I seriously doubt my code is the issue
perhaps I repost in ui
Only for getaxis?
Only for things that aren't already frame independant.
GetAxis returns a value. For example, GetAxis("Horizontal") returns between -1 and 1 iirc. High framerates will apply that 1 or -1 more often than slow framerates, directly affecting speed. MousePosition is just a position, applying that position quickly or slowly won't change anything, but multiplying it by a small number WILL
So, no, not just for getaxis
Okay, that was my mistake. So what's causing his transform issue?
No idea, didn't look 😂
🍻
took a quick look. I would start by logging both the offset and anchored position.
Lol do you have a better idea?
Your offset is clearly doubling from the vid you posted and you didn't post the the debug log from offset and anchored position so...
Why ur getting defensive im curious it sounded like a solution
Anyways im off to sleep thats why I didnt reply to aethenosity
I'm not getting defensive, just thought it might work
I change my keybind icon during runtime, and I get this weird overlapping. I can fix it by in editor toggling the button on and off again. However, I was wondering if there was a line of code I could run that I'm not thinking of that could fix it/referesh it? I tried LayoutRebuilder.ForceRebuildLayoutImmediate(item); however no luck.
If i set my project to use URP i have to restart?
cuz i can't find my pipeline asset
You may need to create a new renderer asset if there isn't one in your project
hey, I have a unity ragdoll and its floating in the air, I have know idea what i should check for.
Hello I've made a function that basically display a big rectangle (character) and a smaller one (weapon) the function is working well and I've made 2 type of rectangle "white one" and "pink one" (see screen) the problem is I've made a list of big rectangle and a list for the small one but when I press the key r the renderer don't change the "color" of my rectangle I don't know why .https://pastebin.com/c5iXtNzM
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.
CreateBuffers(lod);
float[] noiseValues = new float[currentBufferSize];
What are buffers ? Are buffers like boxes in which you put your stuff inside ? Also why and when would you need these "boxes" ?
Can't you just put stuff wherever and use it ? Why some stuff requires buffers while other stuff doesn't ? What determines how big the buffers should be ? How do I know if something is compatible with being put in a buffer or not and do buffers come in multiple types and sizes ? Are buffers hardware dependant or can they be whatever ? Do things work faster or slower when using buffers ?
Way too many unknowns for me. Where can I find the answer to all those questions ?
Also I am observing 3 types of what appears to be buffer specific operations: Create(), Initialize(), and Release(). Why do buffers need to be initialized, aren't they initialized when they are created by being put inside the script ? And why would you release them ? And don't you need to put the stuff back then ? I don't see any operations related to "putting stuff back in the boxes".
It depends on the context. Generally, buffers are arrays of data. And you need to initialize buffers just like arrays.
To answer the rest of the questions we need to know what specific buffers we are talking about.
What is the CreateBuffers function? What context did you encounter this in?
!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.
thanks let me redo the post
public class NoiseGenerator : MonoBehaviour
{
ComputeBuffer _weightsBuffer;
}
private int currentBufferSize = 0; // Variable to store the current size of the buffer
public float[] GetNoise(int lod, Vector3 globalOffset)
{
CreateBuffers(lod);
}
void CreateBuffers(int lod)
{
int requiredBufferSize = GridMetrics.PointsPerChunk(lod) * GridMetrics.PointsPerChunk(lod) * GridMetrics.PointsPerChunk(lod);
if (_weightsBuffer == null || requiredBufferSize != currentBufferSize)
{
ReleaseBuffers();
_weightsBuffer = new ComputeBuffer(requiredBufferSize, sizeof(float), ComputeBufferType.Default);
currentBufferSize = requiredBufferSize;
}
}
void ReleaseBuffers()
{
if (_weightsBuffer != null)
{
_weightsBuffer.Release();
_weightsBuffer = null;
currentBufferSize = 0;
}
}```
Okay, so this is a compute shader.
https://docs.unity3d.com/ScriptReference/ComputeBuffer.html
Ok, so we're talking about compute buffers. These are basically arrays of data that need to be moved between devices(CPU and GPU), which is why there are specific rules applied to them.
Same question just added the code to pastbin
Buffers are essentially packages that can be shipped to your gpu, they have some special operations because you can't just pass whole data to the GPU, the rate is very limited. Buffers can massage the data in ways the GPU can understand to reduce the amount of times you have to do the slow transfer process. Think of it kind of like putting something in one of those special boxes they have at FedEx that are pre-priced, rather than having to weigh and package it yourself and figure out the proper postage for it
A little bit of pre allocation can give some pretty significant speed boosts
So it's like when uploading lots of files to google drive. If you just ctrl+a all the files in the folder and drag them into google drive, the operation seems to take alot of time. But if you archive all those files first, and just drag the archive, the operation seems to take less time. Did I get this right ?
Yes actually. A great analogy.
There's a lot of overhead when sending any data, that is the same no matter how big
So basically between the cpu and the gpu there is like a bridge. And you need to send 200 soliders to the gpu. Instead of sending one solider at a time, you pack them all in a big car and send them that way right ? This way you don't have to send one solider at a time and wait for them to arrive and then send the next one and so on. Is this correct ?
for some reason I cant refrence Cursor in my script, all im trying to do is Cursor.visible = true;
Yeah for the one asking the question you seem to have a pretty good grasp of it
You can think of "Create" as making the car, "Initialize" being loading the soldiers in it, and "Release" being letting them all out so you can send another one
Actually, until a few minutes ago I had no ideas what buffers are and I am preparing to read the documentation you guys linked for them. I was just trying to make a high level idea for the moment at least just so that I go about this with the right mindset, so it's thanks to you guys that I have this view on the subject at the moment 😄
Do you have a script named Cursor perchance
I don't see you doing anything with the renderer when r is pressed. Just changing an int variable.
no
What boggles me about this, is after a buffer gets released, isn't it supposed to be re-used maybe later ? Like what if I want to send another batch of 200 soliders to the GPU, but last time I used the buffer, the last operation was released. So the car is basically on the other side to the GPU. Don't buffers need to be "Called back" to be re-used or does the whole thing run like a loop and I do not need to worry about such things ?
Like does the buffer gets re-created automatically again and "dispatched" again by itself if needed ?
So what is the issue you're having with it
Im not sure, its just not working
Yes but isn't that code ```csharp
if (renderer != null && weaponstypeList[changeweapon] == 2)
{
renderer.material = brownMaterial;
}```` suposed to put "color" to object depending on the if ? because it's the way it work for me
It can be re-used, but it doesn't have to be. Even if you make a new car every time you have to send a squad over, it's still better than sending one guy at a time
Ah apparently I can not use UI.Elements package...
You are using UIElements which has its own Cursor class, if you want to use the built in one, you can use UnityEngine.Cursor instead
Like I made a list of color for that reason but if it's the wrong way then I would be happy to know how to do it properly
Got it, thank you very much for all the explanations.
It can't be reused. On the low level, it's just a reference to the data in the GPU memory. There's nothing to be reused here. Reusing the C# object isn't gonna give any benefit.
Releasing means telling the GPU that that memory is not occupied/used anymore btw. It's more about releasing it on the GPU.
That beings said, you can't send data to the GPU outside of buffers afaik. Even if it's one element it has to be a buffer.
thank you for the tip, glad to see unity keeping their namespace clean clear and concise 
This would change the material, yes. Let me check your code again.
thanks
Ah, that is great then, it means you can't make mistakes (by not using buffers when sending data to the GPU, cause it's the only way to do it) and things will be usually optimised at least from this point of view right ?
I don't see that code in this if block:
if (Input.GetKeyDown(KeyCode.R))
{
changeweapon = changeweapon + 1;
UnityEngine.Debug.Log($"toto a appuyé sur r, la valeur de changeweapon : {changeweapon} {string.Join(", ", weaponstypeList)}");
UnityEngine.Debug.Log($"toto couleur {weaponstypeList[changeweapon]}");
//if (weaponstypeList[changeweapon] == 1)
//{
// UnityEngine.Debug.Log($"element actuelle et sa couleur! {weaponstypeList[changeweapon]}");
//}
//else
//{
// UnityEngine.Debug.Log($"element rooooooooooooooooooooose actuelle et sa couleur! {weaponstypeList[changeweapon]}");
//}
if (changeweapon >= weaponsList.Count)
{
changeweapon = 0;
}
}
Yes. We say "buffers", but it's really just copying memory from RAM to VRAM and keeping track of it. There isn't really anything to optimize.
oh it's when I press p to "make" the "player" should I move it to when I press "r"?
Gotcha, thank you very much for the detailed explanations and advice!
🙏
Obviously. If you want it to change when you press r, it should be in that if block.
ok let me try it thanks
I got this error:
Well, debug it. See the line that throws the error and check what is being null there.
it's that line ```csharp
Renderer renderer = weaponsList[changeweapon].GetComponent<Renderer>();
the thing I don't understand is that it "work" on press p but not on press r
That's why you need to debug - to understand why it doesn't work.
Try using logs or breakpoints to see what is being null.
It's probably the elements in the list.
ok let me see
from what I've understand it only "work" when list index is at 0 but I don't understand why
better print
What is the debug line? When you say "whole list" what actual value is printed there?
so index is just the index like elem nb 9 of the list current element refer to either 1 or 2 for the color of the object and whole list is just the whole list of color
Can you include the weaponsTypeList.Count in that?
ok
I don't get it how I got this error while I have the same list on the print and it was working before ```csharp
UnityEngine.Debug.Log($"list index current element of the list and whole list and weaponsTypeList.Count : {changeweapon} '---------' {weaponstypeList[changeweapon]} '---------' {string.Join(", ", weaponstypeList)} '---------' {weaponsTypeList.Count}");
@sharp oracle You wrote weaponsTypeList instead of the previous weaponstypeList
my fault for writing it that way
I missed that you had a lowercase on the second word
I DO recommend going by standard c# naming conventions, but you can do what you want as long as you stick to your style
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions
Hi, I'm new using Unity and i'm still learning how to write code in C#, and doing a school work for mi programation class this isn't working, Can someone help me plz? Testing different things I reach to the conclusion that the part isn't working is "void OnTriggerEnter (Collider other)" and I don't know how to fix it. (English is my second language, so sorry for any grammar mistake, thnks)
oh I see no problem
I will fix my bug then fix the whole naming convention
you see no problem?
Types vs types
case matters. Those two words are completely unrelated in the eyes of the compiler
fair
no I meant about your mistake
Does one of the colliding objects have a non-kinematic rigidbody attached?
Ohhh, understood
Is my error linked to an non existing elem on weaponstypeList ?
can someone please help me in unity talk
Nope, they only have Transform, SpriteRenderer, Colliders, Animators and scripts
Then it won't work. OnTrigger REQUIRES a non-kinematic (dynamic) rigidbody on one object
Yep. Most likely. One of the elements is null.
but when I print the list none of the element is null
Hmm... also, it's a list of ints, which can't be null. But... something is going on.
What is the actual code on line 81? The line causing the error
Is it this:
#💻┃code-beginner message
Because then the null would be in the weaponsList, not weaponstypeList
Debugging the latter wouldn't help find the issue in that case
I added a dynamic rigidbody 2d to the bullet and the enemy and still doesn't work :/
So, one object has a non-trigger collider, and the other has a trigger collider?
Oh, it's a bullet.
Is it going fast? Is the bullet collider small?
Are you moving it by "teleporting"
(transform.position += whatever)?
Sometimes it can simply teleport past the collider without actually colliding
It would be safer to step through code with a breakpoint. Or break on error and inspect the relevant objects in the inspector. You can enable debug inspector to see private fields.
thanks, how do I enable debug inspector ?
yes, the bullet has a "is trigger" on, should I set it off to make it work?
No, one has to have it
Click the three dots at the top right of the inspector
Does the OTHER object have it set to trigger?
nope, the bullet is big and the collider too and i can see it travelling on the screen so i think it isn't going fast
Well, I would go through this:
https://unity.huh.how/physics-messages/2d-physics-messages
nope
You have the building blocks for it then. Might be another issue
I now got this
The first is likely a false positive (or maybe it's real - internal). The others insist that you've got a reference to null and attempting to use it.
oh I see so what do you think I'm doing understand
I tried to understand since but I don't find it
Can you show the !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.
yes
6
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.
Weapon list at the particular index did not have anything valid. The element was null.
You are printing the wrong list
Oh I'm dumb as fuck
result
code line ```csharp
UnityEngine.Debug.Log($"list index current element of the list and whole list and weaponsTypeList.Count : {changeweapon} '---------' {weaponsList[changeweapon]} '---------' {string.Join(", ", weaponsList)} '---------' {weaponsList.Count}");
Result of what?
pressing r
There's like 5 sec between the error and the log message. What's going on?😅
I just press key r
So does the error come out when you press r or before that? I feel like you're hiding something
I first press key p to "make" the player and little rectangle this work fine but when I press r the error occure
not before
The two did not occur back to back
So when does the debug log print?
just tried right now
when I press r
You should move the log before the error line 81
Unless you changed the order in your code.
ok
I'm guessing element 0 is valid whereas none the rest are.
Ah, I guess that makes sense.
Where the first successfully logs and the rest just blows up with an error
The debug line isn't showing the whole line. I'm interested in the count
Can you show the entire updated code from a link?
yeah
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.
Really hard to read with all these dashes, but it seems like the elements after 0 are null.
do you want me to make a better "print"?
No. Id prefer you to just look at the object in the debug inspector as I suggested half an hour ago. And take a screenshot of it.
Why does it also say NewBehaviourScript
You've only got one weapon in the list
let me add more weapon
wait isn't that supposed to fill the list ? ```csharp
private void Awake()
{
// Appelé avant le Start, souvent utilisé pour initialiser des variables
// Générez un nombre aléatoire entre 1 et 2 pour WeaponType dans Awake
for (int i = 0; i < 3; i++)
{
WeaponType = UnityEngine.Random.Range(1, 3);
weaponstypeList.Add(UnityEngine.Random.Range(1, 3));
if (WeaponType == 1)
{
weaponsList.Add(spawnedEntity);
weaponstypeList.Add(1);
}
else
{
weaponsList.Add(spawnedEntity);
weaponstypeList.Add(2);
}
}
}
weaponsList and weaponstypeList are different lengths
I also have no idea what that if statement achieves
that's true
It's generally bizarre code that is unclear to me, doesn't help that I can't speak french 😄
just to make different "colour"
I know my code is bad as hell it's my fault there
Yes but you could just write:
weaponsList.Add(spawnedEntity);
weaponstypeList.Add(WeaponType);
I just removed the first add on the weapontypelist
now they should have the same lenght
Are the lists supposed to be matched? Could the weapon just have its own type as a property?
There are two other concerns
You are not printing weaponTypeList.Count in that log statement
you print changeweapon
I'm assuming his nre is solved now
It is printed later, just cut off there haha
yes my first goal was just to make 2 different color to make like "2 different weapon" then I found out that doing the render was making the "color" pink and it was fine for me so I stayed with that option
They print weaponsList.Count, it's a mess
Regardless, the error is an NRE, not an index out of range, so none of the prints matter, no?
yes I was printing the wrong list since like 30 minutes
Consider having a struct hold the pair weapon and type in a single list to not have two lists.
how would I in script un-check these check-boxes? I know I can Get Component but then how do I make them inactive?
I had a easier aproch before but it may be way to hard for my current level in unity instead of several color just a square or a circle
but from what I've seen you can't generate a circle from a rectangle object
Can anyone help with a player controller issue here?
GameObject.setActive(false);
this sets the entire thing to inactive, what if I only want some of them inactive?
where GameObject is the object to turn on and off
Assign the enabled property a value of false
https://docs.unity3d.com/ScriptReference/Behaviour-enabled.html
ty!!
Ask the question and someone may be able to help
Thanks, so my character keeps running in circles when I press W
and my camera to look around doesn't work 😦
This is the code channel so you'd want to provide the code. #854851968446365696 for how to post questions.
I think I understand the problem it only work withouth showing error when I use the first element of the list ```csharp
Renderer renderer = weaponsList[0].GetComponent<Renderer>();
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
You've only got one weapon according to your old logs.
yes just saw that by doing test myself
but how I get only one weapon but the len of my list isn't one ?
Orange indicates the null elements. Blue including commas were the elements in the list - notice the blanks between commas.
Green were valid elements which only occurred with element zero
It would be much easier to use the debugger than endlessly iterating on these print statements
thanks
I know but what is this supposed to mean ?
The script asset is totally irrelevant and you rarely need to look at it
why are you looking at the actual script asset file?
isn't that debugger ?
They meant IDE debugger
that ?
It is always worthwhile to learn https://www.youtube.com/playlist?list=PLReL099Y5nRdW8KEd59B5KkGeqWFao34n as it will save you so much time over logging
thanks
after looking searching and struggling I've understand exactly what isn't working
it's that ```csharp
weaponsList.Add(spawnedEntity);
the spawnedEntity I'm adding to my list mean "nothing" to it so it's make like it's not there
If spawnedEntity was null it would only cause an error when it was accessed, and that line does not access it
I see
It is the debug inspector but you're looking at the wrong thing. You should look at the script in the scene on the GameObject. The one that throws the error.
What you show on the screenshot is a script asset, not it's instance.
Is spawnedEntity being null?
I think so , when I print elem 2 so weaponsList[1] it print nothing
I'm currently inside the debug mode of vscode I've added breaking point link to my function but I'm either dumb or idk but it just give this
Nothing means null. I really suggest to go over the c# basics to understand reference types and null.
It doesn't look like it has been triggered yet.
Is your debugger connected to unity?
normally yes
You should not have it attached unless you are actively debugging. Also, what you showed above here
#💻┃code-beginner message
Is not having the debugger attached
In the top middleish of visual studio it shows "attach debugger"
Can anyone help me with sorting layers for a topdown 2d game
how can i make all my sprites in my sprite sheet pivot without breaking everything
i think that is my problem
the sprite sheet is my player sprite sheet so
Hello, I am trying to make an inventory system and was making a method to add armor and weapons to lists for 'currently equipped'. I have two classes, Weapon and Armor, which both extend an Item class. I wanted to use one insert method to simplify and add more scalability to my system. Currently I have: private void EquipItem(Item item) { if(item is Armor) { equippedArmor.Add(item); } else if(item is Weapon) { equippedWeapons.Add(item); } }
Which isn't working because item is defined as an 'Item' is there any way around this?
I also cant make Item an interface since it has monobehavior methods inside it
Curl error 56: Receiving data failed with unitytls error code 1048578 what kind of this error?
If these objects derived from item, I would assume this would work, no?
thats what I assumed would happen, but that doesnt seem to be the case
Strange, well, you can always add like an enum for weapon/armor then assign their type inside of their own respective class and instead check that
Don't cross-post.
Nobody knows the context, elaborate by mentioning what came up when you searched about it
how would I remove an element from an array without resizing?
arr[i] = null
alright, is there a way to do it by object instead of indice?
said objects are not primitives*
Like, clean up an object entirely? You don't really use deconstructors in c#, so if you want an object to be collected by the garbage collector, you'll need to remove all references relating to it.
I moreso meant something similar to List.Remove(myObject) so I wouldnt have to use a loop or lambda to remove it from the list.
IndexOf and then setting that index to null
ah, right
Though you've really got to question why you're using an array
using it for an inventory element displaying armor / weapons (2 different arrays). Since there is a limited number of slots for armor and weapons I figured an array would be best since I could easily limit the size without having to add a bunch of checks
Its not a big deal if I have to, this is more out of curiosity at this point
How many slots?
That's fine if you're not extending your inventory at all
currently 5 and 4 respectively
Then just use a struct
yeah the inventory is a seperate list, these lists are just for the slots
