#💻┃code-beginner
1 messages · Page 139 of 1
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have a problem for this script
It has NullReferenceError while setting the Vector
why is your charactermovement a singleton?
so I can use it as a static variable
and it's because this variable is being initialized before your singleton is created
that doesn't need to be a singleton
Then something on that line is null but you're trying to use it anway
static and singletons should not just be thrown around all willynilly just because you don't want to get a reference the right way
but if I don´t make the CharacterMovement component static then I cant use the PlanarVelocity vector
Why not
look
Yes you can
you absolutely can, if you get a reference to an instance of CharacterMovement
it's like you don't even listen to anything anyone tells you
Yeah, don't do it in the initializer. And this
#💻┃code-beginner message
Why is this a field at all. Just delete bulletVector
And use the value you want in the actual function
you have to run in a Initialization method of some type i believe
you should do this
Thanks
To be clear, you are trying to use _characterMovement before start runs. Thus, it is null. And you can't do it that way anyways
Oh, now it seems so obvious
private CharacterMovement _characterMovement;
private Vector3 _bulletVector;
private void Start()
{
// Assuming you have a reference to the CharacterMovement script
_characterMovement = GetComponent<CharacterMovement>();
// now that you have a reference to your CharacterMovement class you can set the Vector
_bulletVector = _characterMovement.PlanarVelocity;
}```
you would need to assign the reference to the class first..
beit thru the inspector with an exposed variable..
or grabbing it at runtime in a script or something
but ya, unless your using the vector over and over.. (getting rid of it is a good tip)
you can just use _characterMovement.PlanarVelocity; whenever u wanna use that value
otherwise (not knowing ur use-case) you may have to access that everytime you need to use the vector to make sure its updated to the correct value..
or could have just added a funky little > to that assignment operator and turned it into a readonly property to fix the issue
is it bad practice to use public variables and NaughtyAttributes [ReadOnly] attribute?
i have it public as to be able to modify it from external classes..
but it only ever gets read anywhere else.. and also keeps me from changing inspector values by accident
Is it that a lot of search in terms of efficiency?
if u have a reference to it.. not really..
ur just reading.. but its just an extra variable u dont need.. and to keep up with
but if it helps you read and understand the script better, leave it
Accessing a variable is one CPU cycle. You'd need to do it four billion times to take up one second
^ math-person knows whats up
And what if I do that search in Update?
gross
because the vector is constantly changing
if its constantly changing you'd want to access it anytime u need it
if it only needs read when u run a certain function why not read it then
you should stop worrying so much about performance until you actually have performance issues to address
@ionic zephyr this is the best advice so far.. optimization should be left until needed
"if it aint broke, dont fix it" or something like that
Isnt there an alternative?
yea, only update it when you need to use it..
if you need it every frame.. then do it
this isn't really bad practice, but just know that modifying the variable in code at edit time will still be possible and the variable is still serialized
its like a health bar for example.. you can update that every single frame.. but why? you only need to update it when it changes..
so isntead of doing in update.. u would do it instead inside an Attack() function...
it would be called only if you took damage or got a powerup or something
Okay, thanks a lot again
ok good to know..
adding on to this though, i would personally just make the field private and serialize/readonly that but make a property exposing it to other objects. that way if you need to change how it is assigned to in the future there's less refactoring to do and you'll have more control over where it can be modified from
ya, i was trying to think of alternatives but im not that great at properties. and getter setter type stuff
just
[SerializeFieldOrReadonlyHere] private int _myField;
public int MyField => _myField;
is enough for now unless you want other objects to assign to it, then just use a full property or even an autoproperty where you target the backing field with the desired attribute(s)
Yeah there are
I think boxfriend already linked this? https://unity.huh.how/references
Cache the reference (_characterMovement) using a proper reference method
okay thanks
and just do what spawncamp suggested and directly use _characterMovement.PlayerVelocity in place of _bulletVelocity in your Instantiate call. then you don't need to do anything crazy like constantly update your _bulletVelocity variable because you can just access the current value when you need to
how can i instantiate an gameobject with a certain vertical velocity?
like, instantiate it and give it a velocity
instantiate it, then assign its velocity
what is the correct way to code it so my player wont be able to move their camera or player anymore
i tried that
Instantiate it from a rigidbody reference and add the velocity on the line after instantiate
show your attempt
It will work if done right
i initally wanted to do an entiiire if statement on my movemenscript that checks if the player is unable to move or not but i feel like thats not very optimal
you're not assigning the velocity of the instantiated object. remember that Instantiate returns the reference
ohhhhhhhhhhhh
also pass a Rigidbody2D as the first parameter of Instantiate, not a GameObject
i thought it expects a game object? how else would it creae it
Nope. Takes any object (like a rigidbody component)
How do I assign shape to Particle System in code?
you're still not modifying the instantiated object
again, Instantiate returns the new object
but im assigning the new velocity
u mean the prefab?
no, it takes in the prefab as the first parameter and returns the instantiated object
yes
instance = Instantiate
instance.velocity =
You do NOT set the velocity of match
var shape = pfx.shape;
shape.scale = box.size;
shape.position = box.offset;
pfx.shape = shape;```
error pfx is get only
i see
You are assigning the velocity of the prefab which is not the instance
oh so it doesnt work bc it returns the prefab instead
i mean
the instantiated modified one
anyone know what i can call do see which button was pressed when using ipointerdownhandler, idraghandler and stuff?
You aren't returning anything. You were instantiating and throwing away the reference to the instance
left or right mouse button
I don't need to assign it back and it should work?
correct.
Particle System modules do not need to be reassigned back to the system; they are interfaces and not independent objects.
so i need to modify the velocity after the object was instantiated?
thanks!
yes, that is what i told you the first time.
mb
Oh course, or there is no way to modify the velocity, because it won't exist
A prefab is like a blueprint. It doesn't exist in the scene until you build it
modify the velocity of the instantiated object. because Instantiate returns a reference to that object
lemme test that
it will work
*if done correctly
didnt work
ye
it looks good tho
i changed the velocity
after i instantiated it
and what is the value of meet.velocity
No. Specifically what is the value
it changes
you do know words have meaning right? i am asking what the current value of that property is
This will set the velocity of your new object to whatever the current velocity of meet is
Debug.Log if not sure
when the scene starts its 0
but itd change no?
if the game object that meet is set to is falling
Maybe. We have no idea. Check the value using Debug.Log
And where did you log this value? On the shoot method?
Okay now also log instance.velocity after setting it
no, same place as the instantiate one
returns meet.velocity
fr
Sorry I was helping someone else that had a shoot method. Yeah, the instantiate part is what I meant
remember this question
i basically took the input values for movement and camera movement and i multiplied them with the boolean of the player being alive
After setting velocity add this line:
Debug.Log($"Velocity of instance: {instance.velocity}, velocity of meet: {meet.velocity}");
and then show it
wait c# has formatted strings???
Of course
yes, have you not gone through any proper structured course for learning c#? pretty much all of the good ones teach how to use string interpolation
No, many many languages have it
There is very little (if anything?) that python has that others don't
☠️
im trying to makes boids, what would be a good way to group them so they only get boids in the same group as them?
Yep those seem pretty "the same" to me
i learned c# without a course, just by searching stuff up lol
well would you look at that, id does set its velocity correctly. so if it isn't behaving as you expect, then you need to make sure that nothing else is affecting it (like colliding with something or its own code affecting its velocity)
when i set the velocity, will it stay at that velocity or will it accelerate
bc its a rigidbody
It will have that velocity at that moment and will continue to receive any external forces that would normally act on it
i see
be they gravity, collisions, or code
maybe i should approach what i want differently then
i dont think making the velocities the same will work
Is this rigidbody kinematic?
or you could explain what it isn't doing that you are expecting it to do and we can look into reasons why it isn't doing that
dynamic
shouldn't matter. rb2d allows velocity assignment
what are you trying to do
But will a kinematic rb RESPOND to that assignment?
yes
Huh. Alright. Thanks!
That is different than 3d, right?
im trying to instantiate an arrow inside a bird which can jump, but when i instantiate it, the arrow moves away from the bird (they dont collide)
yeah i'm pretty sure 3d rb does not use velocity when kinematic. i haven't really tested it though. but i've done a lot of stuff with 2d rbs
are you sure they don't collide?
Ok. Thanks for the heads up. I don't do much 2d, and what I do isn't using forces
i made the arrow and bird stay together by making it so that any key that moves the bird moves the arrow in the same exact way
but if i instantiate the arrow while the bird is jumping, the arrow will be off position
WAIT
i just tested it
it works
wait why it didnt work before
weird
why does the arrow have a dynamic rigidbody if you want it to move with the other object? why not just remove its rb and make it a child of that object?
hm, is there some kind of major issue with this? it appears that the distance isn't measured
child of an object means they move together?
with the parent
yes, children objects move when their parent objects do. with the exception of dynamic objects like rigidbodies which move independently (though may be influenced a bit by a parent object's movement)
i tried it before, making the arrow the child, ig it didnt work bc it was a dynamic rigidbody
im not sure how the types of rigidbodies work
lol
ill try that then
If its only job is to maintain position relative to another object why does it have a dynamic rigidbody
wouldn't the distance between t.position and hit.point be 0?
hit2's raycast would be a ray of length 0 basically because hit.point is where t.position is
it can be shot
what else type of body would it be lol
wait
let me find out what the different types of rigidbodies are
and ill be bacl
well, no- I think?
hit2 raycast will only fire if the first ray hits a specific collider before reaching the t.position
so a kinematic rigidbody isnt affecred by gravity
i just tried it and the arrow began to fly up once i instantiated it
so you're assuming "hit" will hit something, what if it misses?
then the else on the bottom will fire instead
The else on the bottom fires if whatever object you hit has a tag other than "Forest"
it might not reach the else statement if it tries to peel into the hit object only to find that it is null
oh, huh
if I wanna instantiate an object on the ground (raycast from cam to game)
1️⃣ OnGroundClick(ray.GetPoint(hit.distance));
2️⃣ OnGroundClick(hit.point);
:TIL: about GetPoint
yes, thats what I want
What if the raycast doesn't hit anything
no point in measuring distance then
I only learned it via VS autosuggest lol, although it's still extremely simple to calculate the same without it
Okay so what are you expecting to happen when you try to check the tag of nothing
ah, error
else
{
// Raycast either hit nothing
// Raycast hit something not in our layermask
if(hit.collider == null)
{
// Ray didn't hit anything
Debug.Log("Raycast Missed: Hit nothing");
}
else
{
// Ray hit something, but it's not in the clickable layer
Debug.Log($"Raycast Hit something outside Clickable Layer: {hit.collider.gameObject.name}");
Debug.Log("Please add the object to the Clickable Layer");
}
}```
hehe, im also having a raycast fiasco
There's also the fact that you're trying to use a position as the direction of your raycast
is that a problem?
Well, a position isn't a direction
hey, get out of my head
So that would probably mean your raycast is kind of fucking off into space
I assumed that it sent a raycast towards it
why
you can use a point in space and math it with another point to get a direction
but a singular position isn't worth anything to a raycast
Idk if theres a better way but I use it to start my ray at an offset from the camera in 3d
made sense to me to think that you would have a origin and direction point- right what am I supposed to do if I want to raycast towards a point
ohh thats clever
better than having to introduce a pointless offset variable
Origin point and direction
straight from the documentation
"Hey buddy what's your address?"
"Left."
yeah I read that
and assumed that "a vector representing the direction of the ray" meant that it would be a Vector2 or 3 that showed where to go
ah well, great
thats the bug
ill go and fix it tomorow
It is. It's just that a position is not that
I am aware
Vector2 startPosition = new Vector2(0f, 0f);
Vector2 endPosition = new Vector2(1f, 2f);
Vector2 direction = endPosition - startPosition;
Vector2 normalizedDirection = direction.normalized;
two positions make a direction 👍
i like to walk around in hand-stand pose.. so you would tell me "Right" 😄
oh so I just need to make
a start pos and end pos, like I already have
but then subtract then, and normalize? them
yup that would give u a direction
may need to experiment with the order of subtraction..
may give u a direction opposite of the way u want.. but u can just negate that direction = -direction; to make it flip around the other way
pretty sure its where your going - where you are that gives u the right direction
yessir
great
// Visualize the ray using Debug.DrawRay
Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.red);
thanks
what does the normalization do?
or u can use OnDrawGizmo's or OnDrawGizmosSelected
{
// Create a ray from the object's position
Ray ray = new Ray(transform.position, transform.forward);
// Set the Gizmos color
Gizmos.color = Color.blue;
// Visualize the ray using OnDrawGizmos
Gizmos.DrawRay(ray);
}```
Makes a vector have 1 length
okay
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Can anyone tell me why this piece of code gives my 2D player no x velocity?
{
float tempx = moveInput * (walkSpeed+1);
float tempy = jumpValue * 100f;
rb.velocity = new Vector2(tempx, tempy);
jumpValue = .033f;
Debug.Log("jump " + tempx);
}```
whereas this does have x velocity
{
float tempx = moveInput * (walkSpeed+1);
float tempy = jumpValue * 100f;
rb.velocity = new Vector2(tempx, tempy);
jumpValue = .033f;
Debug.Log("prejump " + tempx);
}```
Either moveInput is 0 or walkspeed is -1 in the first case.
like here, if u have a (1,0) the length from the origin to that point is 1,
if you have a (0,1) the length of the vector is also just 1
but if u were to compound these you'd get the orange dot in the top right..
its (1,1) naturally.. but if u draw a line from the origin to That point you'll see its Longer than (1)
if u normalize it you get this instead.. the vector becomes 1
the same as it did on the other two.. this is used for example in a movement script.. that way when ur giving two inputs (forward and left) for example... you don't run faster
than u would if u were to just go one direction or the other
move input is either 1 or -1 and walkspeed is always 5. Ive checked both with debug log and I actually have both of these pieces of code implemented in the same function so im not sure why one is working and the other isnt
Well, when move input is -1, you have velocity x set to 0. Makes sense.🤷♂️
Im not sure I follow. If moveInput is -1 tempx is set to -6
Oh confused the 2 variables. I throughout walkSpeed was -1.
Well, in that case you'd need to debug.
One of the multipliers is 0
Debug the values that go into tempx.
you can click the kabob menu in the top right and set it to Debug... it will show all ur variables in the inspector.. including the private ones.. can keep an eye on ur values easily that way..
I debugged tempx and that returns -6 or 6 so the tempx value im feeding into rb.velocity isnt 0
or u can use ur standard Debug.Log and log the values u need to watch
Oh ive always just used Debug.Log, didnt know this was a thing
I see that you're debugging it. I'm talking about debugging the 2 variables we were talking about before. Understand?
Here's the updated code.
{
Debug.Log("jump " + moveInput);
Debug.Log("jump " + walkSpeed);
float tempx = moveInput * (walkSpeed+1);
float tempy = jumpValue * 100f;
rb.velocity = new Vector2(tempx, tempy);
jumpValue = .033f;
}```
it returns 1 and 5 when moving to the right
and should be -1 and -5 when moving left
You should probably provide better description in your logs too. As it's now you're gonna confuse the 2 logs.
walkspeed is a constant 5, its just a variable I use so I can easily change the character speed in the inspector.
And when not?
Will do. When Im not moving, it returns 0 and 5
Debug.Log($"WalkSpeed: {walkSpeed}");
you can use string interpolation as well that way u dont have to do the " + " bull crap
Debug the tempx as well.
Ideally all 3 in the same log. You want to see what values they have when the issue occurs.
Well, there you go then. With 0 and 5, tempx would be 0.
but thats when im not moving, in which case I dont want to have x velocity
Then perhaps there was no issue in the first place..?🤷♂️
That's why you should log all 3 at once.
The issue is that Im unable to jump to the right and left when holding down a directional input
it only jumps directly upwards despite having a non zero x velocity
// Debug using string interpolation
Debug.Log($"Jump: MoveInput = {moveInput}, WalkSpeed = {walkSpeed}, TempX = {tempx}, TempY = {tempy}");``` Freebie
Here's a pro tip. Always make sure you're interpreting the issue and the debug data correctly.
And for that you need unambiguous debug data.
Otherwise, you're gonna debug the wrong said in the wrong place.
If a * b = c, and you see that c is wrong, it is probably because a or b is wrong, so you dig deeper to where they go wrong and so on.
Im aware of debugging. Im asking for help because rb.velocity.x is a non-zero number (I've debugged it multiple times) but Im not getting any x velocity. However, here is the full debug log.
Jump: MoveInput = 1, WalkSpeed = 5, TempX = 6, TempY = 9.000152
Well, tempx is not 0
So this is not the case you want to look at..?
Unless the issue occurs at this case as well
Yes, tempX is 6, and im feeding tempx directly into rb.velocity, but rb.velocity is not giving my player character any x velocity
so the game is treating tempx as 0 despite it not being 0
Okay, so the whole debugging was sort of pointless..?
You want to debug rb.velocity as well
*not entirely pointless. It provides a clue that the issue might be somewhere else.
Debug the velocity. Does it actually equal to tempx after setting it?
Debug.Log(rb.velocity.x); returns 6
Great. Should have started with this though.
Now there are a few possibly causes. One likely is that you're overriding the velocity somewhere else. Try commenting out every other place you access rb.velocity.
I see the problem, thank you.
{
jumpValue += 0.1f * Time.deltaTime;
rb.velocity = new Vector2(0f, rb.velocity.y);
}
if(jumpValue >= .09f && isGrounded)
{
float tempx = moveInput * (walkSpeed+1);
float tempy = jumpValue * 100f;
rb.velocity = new Vector2(tempx, tempy);
jumpValue = .033f;
}```
If I want my 2D player character to bounce off a wall is this a suitable way of doing so
{
if(!isGrounded)
{
rb.velocity = new Vector2(-rb.velocity.x, rb.velocity.y);
}
}```
Might want to check the collision direction, so as to avoid bouncing off ceilings and ground.
is there an easy way to do that or would I have to do math using previous positions
I think Collision2D(or the contacts) has a collisionVelocity property. You can use that and dot product to determine how "horizontal" the direction is.
I see, ty. Is there a way to just have collisions be elastic naturally? I saw a video where someone was able to make their player bounce by making a 2d material with no friction and a high bounciness but when i tried that it just made my character bounce against the wall repeatedly while sliding down.
Yes, there are physics materials that can define the bounciness of a surface. They wouldn't work if you set the velocity manually though, as you're basically overriding physics.
mm ok
https://hastebin.com/share/koxagizuxo.csharp help with this, I dont know why my bullet doesnt move
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why can't i make an array of objects containing a script?
what's that?
Components
oh
how should i code the camera lerping to zoom out while looking at the player?
this is how i do it
(in the update function, there is a if statement that when true, runs this function)
however sometimes it doesnt even look at the player
my full code is herehttps://gdl.space/solaniqofe.cpp
A position is not a direction, it makes no sense to pass it to LookRotation
oh
Does the bullet prefab has the bullet component?
(also, obligatory: use Cinemachine)
not the prefab in th asset folder but yes the one in the scene
That doesn't make any sense. The one you want to be shot is the one that you instantiate from the prefab. If it doesn't have the component, the new instance wouldn't get affected by that code.
direction is a direction vector
Oh sorry
the component existi in the prefab
Okay, now the next question is why are you not setting the direction on the new instance of a bullet?
No, it's a vector that logically 'points' in a direction. Positions vs directions the difference between GPS coordinates and saying "North"
I am not?
You are not.
The thing is that in the prefab I introduce in the Serialized GameObject it works
but not in the Instanced bullets
You can't reference an object that doesn't exist yet. What you reference there is a different component that is already in the scene. Not the spawned new bullet.
You mean in the Inspector?
Yes. Whatever you have referenced in the inspector is not related to the newly instantiated bullets in any way, so there's no point in setting a direction for it. Instead you need to set the direction for the instantiated bullets
but it is
look
the present ball moves, which is the one in the inspector
the instanced ones dont move AT ALL
Yes. That's exactly what I'm saying.
why ????????? why does the build do this but the unity editor in game not??
(for context, controls are weird and buggy and the prompt keeps glitching)
when instantiating a prefab, how can i access a child object of it?
like you see this
the instantiate thing
how can i change the positions of child objects in a parent when instantiating
how would i go about setting the direction that my enemies are facing so i can makew their attacks
in a top down game
What would be the best way to pause the game? I've heard Time.timescale = 0 is not the best solution, although I've never really had trouble with it. Outside of that, what would be the best way to pause a game?
First, check the Instantiate docs page. What does the method return?
The simplest way is to set their transform.forward.
Each and every system and controller in your game would need to be implemented with the possibility of pausing in the game. For example, when you're calculating the character velocity, multiply it by some characterTimeScale or something. Set that variable from whatever game/time manager you have.
The good news is that most things should already handle pausing correctly
a clone
Anything that takes place over time will be using deltaTime already
save for a few things like mouse input
so its not possible to use instantiate alone? id have to modify the prefab prior?
which you'll just want to ignore
I don't understand how this relates to your question
how would you access the child object before instantiating?
you can't refer to child objects from a prefab
you should put a component on the root of the prefab that references the child objects you need
and then just grab the references from the component after instantiation
Do you understand the meaning behind it? What does clone mean in your case?
Read the docs Return section what does it say exactly?
I know that everything that uses deltatime gets paused, as well as coroutines which use the WaitForSeconds.
i lost my confidence now lol
u dont really need a coroutine if u dont have to wait and return anything right?
thats just what normal void function does
Yes... A coroutine is for running something asynchronously.
ohhhh
i see
i think of a possibility
because these codes are 6 yrs accumulation of my team, im trying to figure it out
A coroutine lets you run a method that can pause itself and get resumed later
That's the gist.
note that it doesn't run in parallel. It's the same single-threaded code as always.
the clone with the set positions of the child objects
so u cant
this is just a guess, but maybe my team wants to make use of coroutine that keeps running even if gameobject is being disabled
ill find out how to do that
The answer I was expecting is "Instantiate returns the newly instantiated object".
Which makes it totally possible to change it's children position.
of course you can change the position of the instantiate object's children!
public class MyComponent : MonoBehaviour {
public Transform someChild;
}
...
void Foo() {
MyComponent clone = Instantiate(original);
clone.someChild.position = Vector3.zero;
}
You could also mess with the position of someChild in the prefab, I guess
oh
thats the only reason i can think of
you can do absolutely everything you can do with any other object
You can access them with transform.children at the very least.
We can't really say anything without seeing the code you're talking about.
so my team lead gave me an answer, simply for heavy event based functions, or functions that contains huge tasks, like instantiate+setup a gameobject , we will use coroutines to simulate multithreading
That's... Not really how it works... It still runs on the main thread...
Though, I guess if the setup is heavy you could break it down to several frames. Hard to say anything without seeing the implementation.
because they believe that ,
startcoroutine(funcA())
funcB()
yes, they think after funcA is called, funcB will also call while funcA is doing its job
funcB would be called when funcA gets to it's first yield return.
it's not while funcA is doing its job. it's after funcA gets to a yield return and decides it's done running for now
Unity will resume the enumerator returned by funcA sometime later
Because they are. They are functions. There's no such thing as "void function". Void just describes lack of return value.
And IEnumerator is just a function that returns an IEnumerator with some additional logic involved.
as u see, theres no yield return at all
this accomplishes nothing
precisely
yield break was added at the end because the compiler demands you have at least one yield statement somewhere
This coroutine would complete entirely before UpdateDimMask is called.
this is just a "wannabe" multithread
It's not gonna make it multithreaded or async just because you treat it as a coroutine. It actually needs to yield return for it to work async.
ikr, the coroutine will do all the stuff before doing other things
that yield break looks sus to me at first glance already
Tell your team lead to go back over the basics😛
lol
that is not a problem in itself
although its presence is certainly weird
so, true, it is sus at first glance!
i used to think coroutines were magic
multithreaded, running-at-the-same-time, etc.
lemem tell u, all the functions that includes setup + instantitate are all using this kind of approach
no, they're really really basic! they're just enumerators!
they are everywhere
oh boy
also this doesn't even look that expensive lol
20 +
i guess it could be slow if it needs to fetch that thing from disk
just a single manager contains 20 + of these kinds of functions
no, i just checked, all dialog setup is pure local
the data is fetched from server at very first, this function is utilizing it only
I don't know the whole context, but it's fine for the team lead to not know details of implementation sometimes(unless they wrote that code). It is their responsibility to not make assumption and confirm with the docs before giving explanations though. If that code was delegated to someone else to be written, it should be handed back to them for rewriting.
as i said, these codes are accumulation of 6 yrs, so most staffs that wrote these are left
I see
Send them an email with threats. Stalk them to their doorstep. Make calls and breath heavily.
this team is on final stage, like optimizing stuff before production
yes, optimizing lol
i mean, it certainly won't hurt the game
it'll be marginally worse than just not doing a coroutine at all
It probably just adds some overhead in this case.
i told the team lead to just use normal function on first sentence
does someone know if i have two box colliders on a sprite, how do I specify the collider I want GetComponet to get?
You can't really. Generally you either have different shapes, or have one or both as separate child objects
ok ty
You could get all of them and check the size or some property I guess. But that seems like a brittle way to do it
yeah, il just add them as children
private void GenerateSocketErrorDialog(DialogType type, string msg, Action OkAction, string[] args = null, bool isWaitChangeScene = false, string errorCode = null)
{
var prefab = Resources.Load(dialogPath + type.ToString());
GameObject dialog = GameObjectInstantiate(prefab as GameObject);
CommonDialog msgDialog = GetComponent<CommonDialog>();
//Reset flag
RoomManager.Instance.onclickingGameJoin = false;
//login error and normal error
msgDialog.SetDialog(msg, OkAction, null, DialogMessageType.Default, args, isWaitChangeScene, null, errorCode);
msgDialog.Truncate();
AddDialog(dialog);
}
this is the one i modified
public Image oldImage;
public Sprite hiraganaChart;
void Update()
{
// Detect if the ` key is pressed
if (Input.GetKey(KeyCode.BackQuote))
{
Debug.Log("Backquote key pressed");
changeImage();
}
}
public void changeImage()
{
oldImage.sprite = hiraganaChart;
}
How do I un change image on the "upstroke" of the keyboard? i.e. back quote is pressed, changes image, then unpressed and the image reverts
I have to make this cannon shooting at meteors game but i don’t know how to make a bullet come out the cannon
It’s a 2d project
I would look into prefabs and Instantiate in unity docs. The bullet should be a prefab and you can use Instantiate in script to spawn the prefab. After it is created, you can use Object.AddForce() to add velocity. Just make sure you have a method that destroys the game object.
void FixedUpdate()
{
Vector3 angles = GetAnglesFromCurve();
Quaternion rotation = Quaternion.Euler(angles.x, angles.y, angles.z);
Quaternion lookRotation = Quaternion.LookRotation(rotation * Vector3.forward, Vector3.up);
transform.rotation = initialRotation * lookRotation;
Vector3 posChange = currentSpeed * Time.fixedDeltaTime * transform.forward;
transform.position += posChange;
}```
rotations make my brain melty, but can anyone tell me why LookRotation works here such that the angle of rotation stays consistent such that my initial rotation wouldn't affect how this object travels
like, why isn't initialRotation * rotation enough to satisfy the initial rotation relativity. Even something like rotation * initialForwardDirection
You want these two:
Or you could do something with checking if an input method is false/use an else statement.
This was it, thank you
How do I reorganize the image layers? I want the on in the back to be up front I tried setting the layers but no dice
Order in the hierarchy
It's ordered above the inputfield and image already
In 2d renderers in the inspector, there's an option for sorting layer and order in layer, typically under 'additional settings.' If you are using a UI element without a renderer, then you can add a sorting group component which has the same settings.
the component overrides the renderer settings, incase you were curious
Where are the additional settings?
That's a UI element, so you have to add the sorting group component.
No dice
Set the Inputfield and image to in sorting and 0 for the hiragana chart
hmm. I hade this issue with another project of mine. Let me open it up and see if I recall what I had to do
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I just found out about navmeshes and what a miracle this is. Whoever wants to make an enemy AI for example, nav meshes makes it so much easier
I was actually suffering until I found out nav mesh
Im currently working on a really basic game and plan to set up the powerups tomorrow, would it make sense to have the player pick them up by detecting a collision of a tagged object(the powerup) which could then set a variable that resets itself after a set time?
i havent tried to make powerups before and am hoping that they arent to complicated 😅
Does anyone know why I have to use the default constructor in this script? If i use
private void Awake()
{
bitBoard = new ulong[12];
prefab = new GameObject[12];
}
private void Start()
{
bitBoard[(int)PlayerPiece.wPawn] = 0x000000000000FF00;
...
or:
private void Start()
bitBoard = new ulong[12];
prefab = new GameObject[12];
bitBoard[(int)PlayerPiece.wPawn] = 0x000000000000FF00;
...
It doesn't work. Only this works and I don't know why:
public class GameManager : MonoBehaviour
{
public GameObject[] prefab;
public ulong[] bitBoard;
private GameManager() // has to be GameManager()?
{
bitBoard = new ulong[12];
prefab = new GameObject[12];
}
private void Awake() // Start() also works here
{
bitBoard[(int)PlayerPiece.wPawn] = 0x000000000000FF00;
bitBoard[(int)PlayerPiece.wKnight] = 0x0000000000000042;
bitBoard[(int)PlayerPiece.wBishop] = 0x0000000000000024;
bitBoard[(int)PlayerPiece.wRook] = 0x0000000000000081;
bitBoard[(int)PlayerPiece.wQueen] = 0x0000000000000008;
bitBoard[(int)PlayerPiece.wKing] = 0x0000000000000010;
bitBoard[(int)PlayerPiece.bPawn] = 0x00FF000000000000;
bitBoard[(int)PlayerPiece.bKnight] = 0x4200000000000000;
bitBoard[(int)PlayerPiece.bBishop] = 0x2400000000000000;
bitBoard[(int)PlayerPiece.bRook] = 0x8100000000000000;
bitBoard[(int)PlayerPiece.bQueen] = 0x0800000000000000;
bitBoard[(int)PlayerPiece.bKing] = 0x1000000000000000;
for (int i = 0; i < 12; i++)
{
InstantiatePeices(bitBoard[i], i);
}
}
private void InstantiatePeices(ulong value, int pieceIndex)
{
BitArray squares = new BitArray(BitConverter.GetBytes(value));
for (int row = 0; row < 8; row++)
{
for (int col = 0; col < 8; col++) {
if (squares[col + row * 8])
{
Instantiate(
prefab[pieceIndex],
new Vector3(col, row, 0f),
Quaternion.identity );
}
}
}
}
}
I read online that Awake() and Start() are preferred over default constructors for MonoBehaviours, but there are apparently some exceptions. Is this one of them, or am I just doing something wrong?
I don't see anything here that would require a constructor. What exactly is going wrong?
And yeah, you shouldn't be using constructors with MonoBehaviour.
keep in mind that public variables will be serialized so after the constructor runs unity applies the serialized arrays, which are probably empty if you haven't assigned anything in the inspector
The problem is probably you overriding the prefabs array with nulls.
In awake or start. When you move it to the constructor, it's probably not executed, so it doesn't cause the problem.
I’ve been unable to make a character move around and jump about in my 3D game
It’s been frustrating, the character can move but just can’t jump
show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You'd have to share a lot more info for anyone to be able to help you with that
Yes sorry didn’t say anything yet cus i was waiting for my unity project to load first
Someone please?
this is a code channel
I'm not too sure if it will be possible to do with just joints, so that's why I ask here, to find another way.
Imported a character from mixamo and made this in the animator
Hold on while i show you the script too
lol dude.. is that a photo of a screen?
what on earth
Can’t screenshot
why not?
Laptops been bugging for a week
that's a very strange bug
https://screenshot.help
also you know this is a code channel, right?
Everything’s been freezing
No i tried i literally can’t screenshot
i’m sending my laptop for repair soon
Ik its a code channel but the animator is related to the problem im facing with the code
and you still haven't bothered even sharing the code despite having been asked to like 45 minutes ago
? my laptop has been freezing and refreshing, ive been trying
i already mentioned it being slow and freezy, ive been trying to open the unity code
how do i share the code?
just copy and paste?
with the link you just posted then deleted.
and don't multiply your velocity by deltaTime
im like only 2 months new to unity coding
so spare me not understanding some stuff
and if the object is still not moving then you need to make sure your animations are not controlling the position of the object otherwise they will override the position
currently, the character moves just fine, left and right, front and back, sprints and walks but I just don't know how to do the jumping part
thats the main issue w my character
ah so you aren't having trouble with existing code. you just don't know how to implement a jump
plenty of resources online about how to check for ground and apply an upward force or velocity to a rigidbody
yesyes, everything implemented right now works just fine, i just dont have a clue on how to get the jumping part
and the tuts ive watched on yt
let me guess, they haven't worked?
nope
and that's probably because you are overwriting velocity every FixedUpdate
they just show a capsule as the character and never shows how to do it with a real imported character w animations
oh
spoilers: ||it works exaclty the same||
as in with a capsule object theres no animations, it just moves
ill
figure that out
wait so do i remove that fixedupdate?
so? jumping has nothing to do with animating. you can pass parameters to your animator however you'd like. that doesn't mean your animator has anything to do with how you are actually implementing the jump in physics
right right
ill handle that later as i have another submission that I gotta give by midnight which is 12 hours from now but its much simpler
its a 2d cannon game where the cannon is fixed at the bottom and can turn left and right to shoot bullets, there are meteors fallling down at a random range which will get destroyed if the bullets hit them
and theres like an interval to which the bullets are fired
thats all there is thats required
issues ive been facing are not knowing how to implement bullets being fired from this 2d sprite cube
I cannot find the tools window in unity urp
get direction of fire, instantiate object at desired position facing desired direction, apply movement in your preferred way to move projectile
- this is a code channel
- what tools window are you referring to
The tools window
do you mean the Tools dropdown menu in the toolbar? that only appears if you have some asset or code that adds something to that menu
first of all, that screenshot is so small that the text is literally not legible.
and second, the Tools menu will only appear if something in your project is actually adding something to that menu
But I added a asset which uses tools window
are you sure about that?
Yes
then check your console for errors
Yeah I have one
well then you probably need to fix it
Wait
[Worker0] Failed to load 'C:/Users/SOHAM PAL DEBASHIS P/car/Assets/Car-Controller-master/ProjectSettings/XRSettings.asset'. File may be corrupted or was serialized with a newer version of Unity.
the error
this is not a code issue. you may need to restart the editor or something 🤷♂️
the file was deleted by me rn
The issue is it only works with a constructor, not that it doesn't work.
that would work just fine if you assign those arrays in Awake
You'd think so
because it would
But it doesn't
Yes, that's what I said. It works with the constructor since you done run the faulty code(assumption).
prove it
MonoBehaviours can't have constructors. Initialize the array either in the declaration, or before you attempt to use it
and that has nothing to do with when you create the array instances. the object you are passing to Instantiate is null which means your prefabs array contains null elements
it's caused by passing a null object to Instantiate
Ah, so the actual line is in the stack trace probably
yeah
Show the full stack trace of the error please
what does that mean
They initialize the array in awake and start with nulls, which causes the issue. I'd assume the constructor doesn't run at all, preventing the faulty code from running.
When you click on the error, show the stuff in the bottom window
oh you know what, i know exactly why this is happening and it's exactly what i told them earlier
they have assigned values in the array in the inspector because these arrays are serialized. the serialized values are applied after the constructor runs
but if they create new instances of the array in Awake then of course those serialized values will be overwritten because Awake happens after that
Yeah this isn't needed
bitBoard = new ulong[12];
prefab = new GameObject[12];
I'm pretty sure the constructor doesn't run at all
nah, parameterless ctor should run when unity creates the instance
it's just that deserialization happens after the ctor has run
Okay, so it worked with the constructor because it was overwritten by the assignments in the instructor, but it didn't work with awake because it's overwriting the assignments in the instructor
makes sense
correct. because your arrays are public and of a serializable type so unity creates the instance for you and uses whatever is in the inspector when it creates the instance of your monobehaviour
Such a confusing order of operations. Best to just avoid them I think
yeah, really only useful if you actually know what you are doing
Well I'm glad I asked despite it 'working'
just to make sure
if (GameManager.Instance.isPaused)
{
msg = "ERROR_CONNECTION_FAIL_FROM_BG";
}
#if DEV
else
{
msg = detail;
}
#else
else
{
msg = "ERROR_CONNECTION_FAIL";
GenerateSocketErrorLogs(detail);
}
#endif
this will work right?
yes, but why bother including the else and the brackets in there? why not just wrap the statements themselves in the conditional compile directives?
it's just a secret pre-awake where most of your shit gets overridden 😄
if (GameManager.Instance.isPaused)
{
msg = "ERROR_CONNECTION_FAIL_FROM_BG";
}
else
{
#if DEV
msg = detail;
#else
msg = "ERROR_CONNECTION_FAIL";
GenerateSocketErrorLogs(detail);
#endif
}
guess its just me braindead lol
either way works, i personally just perfer the latter so i know i'm not fucking up any braces in the non-compiled code
methods dont require you to write it, it will just default to private if you dont write any
im not entirely how unity does it, and i dont think its really known either (could be wrong on that). it doesnt really matter, they could be using their own messaging system or reflection.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
on the docs they do list all the methods as "Messages" for things they call like this
Don't know if this is the right place. I'm using a basic starter asset for a first person player to test some prototyping, and am trying to figure out how to handle the main camera. I don't suppose you would just add it to the prefab? Tried that and it didn't work out
don't make the camera a child of the player. and you should consider using cinemachine
Cinemachine, sounds fancy. Gonna have to look into that
they use reflection
its fine if you don't really care about how it ends up looking, so for just learning sure it's alright. but if you want the camera to actually feel good then you won't do that
Hi all... I have a cylinder with a ridgedbody component and I'm trying to figure out how to make it lean over. This would be as if it was hinged at its bottom. I looked at AddRelativeTorque() but couldn't make it work right. Is that the proper method?
what kind of effect are you trying to get, usually RB's have their rotation locked so it doesnt fall over. if you dont lock the rotation, you'll need some other way of balancing the player. you can probably get away with just directly rotating the model
Well it's floating, and I want it to respond to wind or current
But its anchored
If I rotate it, it will turn at its center.
Even hinging at the base is not exactly right, ideally I'll do some trig and figure oiut the new position, accounting for the anchor line.
honestly got no clue what effect you're trying to do. hinging, anchor line, these make no sense to me at least. not sure what you expect to get from a single cylinder
if this is a global variable, theres no difference. itll be initialized to null anyways
if its local, like inside a method, then the compiler will complain even if u try to do if(input == null)
yea
this is scoped to the class, it becomes private to Foo, FYI.
guys i have a question if you like uh learn 2d game coding and use the code that learn from making 2d games for 3d game will it still work?
there really isn't a whole lot different between 2d and 3d when it comes to code
Hi, just wanted to know if this is a good or bad way or what can be improved.
I have a player that has 2 child gameObjects. These 2 child object just have 1 Collider each. One child is a "hitbox" and the other is a "magnet" (for picking up items).
The player itself has a controller script and a health script - that health script implements an Interface IDamageAble
When the hitbox script will detect a collision with enemy it will access the health script and decrease its life.
This is the little snippet :
void OnTriggerEnter2D(Collider2D other)
{
IDamageAble damageAble = other.GetComponent<IDamageAble>();
damageAble.TakeDamage(10);
}
How can this be improved?
ty browj
Im not a big fan of using interfaces here, it's not really needed. Health (or stats in general) can just be made into 1 script that works for any object. For example an enemy taking damage vs a player taking damage is the same thing, so different scripts dont need to implement IDamageAble
Hmm, I try to wrap my head around this. The health script, at least that was my plan will be attached to both the player and enemy. So that means I don't need the interface, since they share the same script? Is that what you meant?
Yea, theres only one script so no need to make an interface for it. I can't imagine many scenarios where you need to handle it differently, its always going to be just subtracting from a float. And you can also add alot of options to the health script so it works for different objects
At the end of the day, itll have the same effect. I highly doubt you'll have a 2nd script implement IDamageAble
Oh yeah you are totally right. Thats the reason I asked, i kinda felt something is a bit off
the whole component vs interface debate for this is really just personal preference.
what isn't however, is null checking that object returned by GetComponent. you wouldn't want a bunch of errors if it hits something without an IDamageable or health component, so you should switch to using TryGetComponent instead of just GetComponent because it combines the null check and getcomponent call all into one line
Next step is that the health script emits an event - so the GameManager will pick it up and then go in gameover state ? Or should the health script go into gameover state when it's 0 ?
good point thx 🙂
Ah yea didnt even notice that get component thing
event 100%
don't make your health script manage the game flow, let it alert other objects that it has reached 0 so that they can react, like your GameManager can react to health hitting 0
An event sounds fine for this, whenever you spawn the player you can just pass its health script to the game manager
In a bit more detailed, how would this event look like? Like PlayerDamaged(int remainingLife) and the gamemanager then checks if it < 0 ?
An OnDeath event would be fine here, game manager probably doesnt care if you are 1 hp or 2. It cares if you die
Since health is on both enemy and player I kinda need a second argument to let the gamemanager to know if it is the player or enemy that hit 0 hp right?
Neither player or enemy would know about the game manager, the game manager subscribes to the event itself
just don't make the event static and only subscribe from the gamemanager when you spawn the player
void CheckPlayerDead () {
if(gameObject.tag == "player" && hp <= 0) {
// dead.invoke()
} else {
return;
}
}
``` something like that?
what, why
just check health, don't worry about the tag
that way you can use the event for enemy things too, like tracking score, keeping count of how many are alive, etc
yes but the health script is also attached to enemy, and when its an enemy that died, i want to emit another signal or something like that
why does it have to be a different one? just have one OnDeath event
Your health script shouldnt be concerned if it's a player or enemy, the game manager wouldnt subscribe to that enemy event and thus it wouldnt affect anything
Ok, lets say a enemy dies and i emit OnDeath, the game manager picks it up and then he checks if it is the player and then goes into gameover state?
Nothing here should be checking if it's the player
why would the game manager subscribe to an enemy's OnDeath event? again, don't make it static
ahhh ok im dumb
got it
the manager isnt subscribing to the script, but to the instance that has this script, and this is just the player instance, got it guys so helpful
With 1 player and 1 enemy, they both have their own instance of the event. It's like how there are different news outlets. You may to subscribe to one and receive newspapers, but that doesnt mean other news outlets send you papers too
Yea you got it
it clicked, thx so much - now that i have a rough plan I will try to make something simple with it
Hello, I really need help with my script. I'm trying to move the ball by moving the mouse forward, etc. Like "Hyperbowl" game if anyone knows it. can anyone take a look at my code? if they have experience with this movement
don't crosspost. and see #854851968446365696 for what to include when asking for help
why not just one object that contains all of the different stats as fields or properties
well creating a class for each individual skill is silly. You could instead create a Skill class with the level and modifier values
Okay, I thought it's best to include it in all 3 coding channels as I don't know where it should belong
yes
they still wouldn't need to be different classes for that unless they needed different behavior
you wouldn't go and make a "OrangeCat" class and a "BlackCat" class when you have two cats that share the same behavior but just have different values for things like color
right
This the right way of creationg my died event on the Health script? What is the naming convention for delegate / event etc?
public delegate void Died();
public event Died died;
Invoking it:
public void TakeDamage(int damage)
{
StartCoroutine(FlashSprite());
amount -= damage;
particles.Play();
if (amount <= 0)
died?.Invoke();
}
you don't even need to create a delegate for that, just use System.Action
oh yeah that's even better thx, and the event itself, can I capitalize it? Or capitalize because it's public?
up to you whether you want to follow standard conventions or not. but C# naming conventions state that public members should be PascalCase
Alright thx, now the last piece of the puzzle, am I doing it the right way?
public class GameManager : MonoBehaviour
{
private Health _health;
void Awake()
{
_health = FindAnyObjectByType<Health>();
if (_health != null)
{
_health.Died += PlayerDied;
}
}
void OnDestroy()
{
_health.Died -= PlayerDied;
}
void PlayerDied()
{
Debug.Log("Player died.");
}
}
Oh *** no its not right, I will search for any health script wait a sec
i for sure would not use any of the Find methods to get a reference to the Health component. if the player is already in the scene at edit time, just drag the reference in. if it is spawned by something, then have whatever spawns it pass the reference
Ok 100 % right
public class GameManager : MonoBehaviour
{
[SerializeField]
private Health _playerHealth;
void Awake()
{
_playerHealth.Died += PlayerDied;
}
void OnDestroy()
{
_playerHealth.Died -= PlayerDied;
}
void PlayerDied()
{
Debug.Log("Player died.");
}
}
That should do the trick
When my weapon hits an enemy or obstacle, i will spawn particles at the location it hit. Where should that particle system reside? On the weapon? Or globally in the scene, spawning at location of hit? Interface with IParticleEmittable or something like that and then the thing i hit, that has this interface, will spawn the emitter at its position?
Followup question to that: So for example if I have a spawner that spawns the player (just for science, doesnt makes sense i know) - the spawner will have a reference to the GameManager (dragged in, since its there at edit time) and then it will add the player like gameManager.PlayerHealth = spawnedPlayer ? And do I also need gameManager.PlayerHealth.Died += gameManager.PlayerDied
What is a MonoBehaviour
A type.
Depends on how you want to design it. You could spawn the particles from the weapon, since it's the closest thing by the responsibility. Alternatively you could have a particle manager to handle all the particles in the scene and the weapon would just make a request to it.
With your example it would be wiser to call GameManager.SetPlayerCharacter(player) or something and do all the other internal logic(like subscribing to events) inside of it.
Thx that makes sense now, something like that (in GameManager):
private List<GameObject> _enemies = new List<GameObject>();
void AddEnemy(GameObject enemy)
{
_enemies.Add(enemy);
Health enemyHealth = enemy.GetComponent<Health>();
enemyHealth.Died += EnemyDied;
}
Yeah, that looks good.
One thing that feels a bit off to me is that health script emits the Died event and not the player script itself. But I think it's just the naming itself. In my head it reads "when health dies do x ..."
ReachedZero()? 😄
It does sound a bit fishy. Maybe nest that in the player script and reinvoke the event from the player script.
I'm sure player would love to do some logic when it's dead too.
so you mean the player could subscribe to this event and then invoke its own Died event?
Yep
ok got it thx
enemyHealth.Died += EnemyDied(enemy); what about this? How can i pass in a argument to the GameManagers "EnemyDied" method?
Maybe you have some ability to install revive the player and it's defined on the player? You can then avoid invoking the player died event and instead restore health. Just an example.
yeah got you makes totally more sense doing it like you suggested great info
In gameManager:
enemy.Died += onEnemyDied;
In player script:
health.OnZero += OnHealtReachedZero
If you're using Action, then just Action<ArgType>
ah thats it yeah, did that now
you pass the parameter value when you invoke the action not when you subscribe to it
Have it like this now and it works 🙂
public event Action<GameObject> Died;
Died?.Invoke(gameObject);
{
bool isWall = other.gameObject.CompareTag("Tiles");
if (isWall){
Vector2 normal = other.contacts[0].normal;
rb.velocity = Vector2.Reflect(rb.velocity, normal);
}
}```
I have a bullet that i want to bounce clean on walls without loosing velocity, meaning it should bounce indefinitely, but i can't get it to work consistently, probably because the bullet physically hits the wall aswell. Any ideas? Should i Ignore the collision for 1 frame after each collisionenter2d?
How do I go about applying velocity to a Third Person Controller when pressing a certain button?
From something like swinging on a rope
Because whenever I pressed the space bar to jump off, it just keeps plummeting to the ground
well, if you're parenting/attaching the player to the rope and using the rope to guide the player then you need to also transfer the velocity over to the player when disconnecting from the rope
This is what I have, codewise.
I'm sure it should be transferring the velocity over but it doesn't whenever I have the Third Person Controller Script enabled. Otherwise, it works as intended.
I have a rigidbody on my character and everything
Isn't the third person controller a kinematic controller? It doesn't use a rigidbody to move?
Yeah, because I couldn't find anything about rigidbodies in the script
I added one onto the character as a component
They're going to conflict
Manually calculating the physics. Or you keep what you're doing and apply the velocity to the player controller you use for actual non-rope movement as the new velocity.
Or you commit to using a rigidbody movement controller for everything outside the rope as well and keep it all within the same system.
So by disabling the third person controller when swinging on the vines and replacing it with a rigidbody one?
You implied you were disabling the controller when you were swinging and activating the rigidbody instead. Then swapping them back after you release.
Yes
So when you swap them back the other way, when you turn off the rb and turn on the controller, you need to take the velocity of the rb and apply it to the controller.
Or as above, drop the controller and use a rb for everything
how can I make my platforms with a linear movement? because It starts to slow down when it reaches its destination with the Lerp vector
Hi guys in my gamemanger I have this function that a enemy spawner will call. Is it better to write it either this way:
public void AddEnemy(EnemyController enemy)
{
_enemies.Add(enemy.gameObject);
enemy.Died += OnEnemyDied;
}
or that way:
public void AddEnemy(GameObject enemy)
{
_enemies.Add(enemy);
enemy.GetComponent<EnemyController>().Died += OnEnemyDied;
}
What would you prefer and which one makes more sense? Any other mistakes I've made maybe?
lerp between the original pos and the final one, not the current and final
or just add the same value to it each frame
both work
Use the MoveToward function instead of Lerp
Or as above, lerp the start and end position
you mean between point A and point B or the transform of the platform?
Oh, of course, thanks a lot!
so basically when i add using System LINQ my current code breaks because it thinks I want to use LINQ instead of some other package
Its working until I add System LINQ.
But I neeed LINQ for something else
I'm pretty sure it won't like that massive gap you've got there
i need to somehow force it to use a specific package
How should I check that my Platform has reached point A or point B?
OMG, do you have any idea what that line will do to your performance?
its gonna use findobjectoftype every frame until it finds right ?
yes
so you suggest to search every 0.1f of a second instead?
no, find another way of doing this
Why can't this thing just register itself instead of constantly querying every object in existence
Or find a better way, like have things register themselves with the system as needed
i see will think about it
Yeah I need to stop using findobjectoftype constantly haha. its coz it works fast on my pc that i dont replace it with faster methods
but its better to get rid of it
It's fine to use, properly, in appropriate places
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
my platform doesnt move
like at All
like a find object of type during a 1 time awake here and there sure cache it once and use it
per frame on multiple objects and you are approaching a problem wrong
Can 2 colliders that are triggers trigger collision / trigger enter?
sorry I didnt find what I was looking for, could someon explain?
No , read it and understand it. What anyone will say is all in that post!
Don't try and put it into your scenario straight away, follow it.. do the examples.. learn.. and then play with it and change for your needs
When it comes to transferring the velocity from the rigidbody to the (kinematic) third person controller, which script does it need to be a part of? The vine swinging or the third person controller script?
Is there anyone who knows about Photon Engine Multiplayer system in Unity?
I have one HitboxComponent that has a collider that is also a trigger. Now i have a player and an enemy and both have this component as child. When I move with the player to the enemy, the OnTriggerEnter2D for the players fires 1 time and the OnTriggerEnter2D for the enemy fires 2 times - any idea why?
Code:
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log(tag);
Hit?.Invoke(5);
}
Log:
Enemy
Enemy
Player
Hence the enemy always takes double damage. What am I doing wrong?
Nervermind! My player has a second component that is also a trigger called PickupRange, is there a way to check for collider name or something?
yes, by if statement
https://hastebin.com/share/egogejofun.csharp could anyone tell me why it doesn go the other way?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
no built in way btw, write it yourself
because the check completes itself
but the change of points doesnt
_OriginalPosition = _PlatformObjective;
_PlatformObjective = _OriginalPosition;
int x=10,y=5;
x=y;
y=x;
what is the value of x and y now?
if (other.name == "Hitbox")
{
Debug.Log(tag);
Hit?.Invoke(5);
}
``` solved it
terrible way of checking for stuff
by name
do it by getcomponent or even tags
Yep I will add some tags thx
it works! thanks a lot
Can you not use operators on shorts? Why's it red? It shouldn't need casting.
Hey there. I made a script to aim these turrets on this ship... When this spaceship moves. The hole thing shits itself. Any help?
Also my braincells can't handle adding turnspeed... Optionally it would be great if someone could help me on that front too.
Code:```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurretAim : MonoBehaviour
{
public Camera camera;
//public float maxTurnSpeed = 90f;
public int minRotationAngle = -45;
public int maxRotationAngle = 45;
private bool camExistis = true;
[SerializeField]
private bool lockZRot = true;
private void Start()
{
if(camera == null)
{
camExistis = false;
}
}
void Update()
{
AimAtMouse();
}
public void AimAtMouse()
{
Vector2 mousePos;
if (camExistis)
{
mousePos = camera.ScreenToWorldPoint(Input.mousePosition);
}
else
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
float angle = -Vector2.SignedAngle(this.transform.position, mousePos);
angle = Mathf.Clamp(angle, minRotationAngle, maxRotationAngle);
this.transform.localEulerAngles = new Vector3(0, angle, 0);
}
}```
IEnumerator late(CustomYieldInstruction delay, Action act){
yield return delay;
act?.Invoke();
}```how to use this? What kind of instruction can i feed in `delay`?
Did you check the docs? 
me just did :3
I'm guessing you're trying to schedule your async/await?
no, im trying to make sure some methods are don in EndOfFrame, but realized I should use just YieldInstruction for those
pass in your object/class that derives from CustomYieldInstruction
ah yea? mj just enlightened me like earlier
it's similar to this
public IEnumerator Foo(Action func)
{
yield return new MyCustomYield();
func.Invoke();
}
just like regular coroutine
Is this a good idea (hurtbox and hitbox)?
depends on the game
currently in the beginnings of learning unity with a vampire surivors clone
Why aren´ t my materials working even if I assigning them to the Colliders of Objects
well, if you want to make an enemy that is like a goonba with a big spike on its head, and is vulnerable on the main body, then it makes sense
to make spike a hitbox and body a hurtbox
i tought it would be nice that enemies have a small hurtbox but a bigger hitbox
it depends on the type of game, really
i would expect for an FPS to only need 1 hitbox
since enemies don’t do dmg on touch. it’s the objects and projectiles they spawn or whatever that have hurtboxes
for mario, might be good to split up
for smash bros, characters don’t have a normal hitbox active on them at all times
for sonic, you definitely want to split
Do materials need a RigidBody?
physics materials live on rigidbodies
but also in Colliders
i don’t think so
maybe it is different for 3D
i don’t recal if colliders can have different materials
Assuming you mean Physic Materials and also the other way around, no. Only if you need to change the default friction or bounciness
in 2D, colliders without RB are assumed to have a static RB on them
Oh okay so for the friction and bounciness I need a collider 100%
or rather, they behave as though they have a static RB with settings that don’t change anything you set on the collider
Okay, I think I understand
the CharacterController´s collider doesn´t interact with materials then, right?
it's a great idea!
that's how I did hit/hurt boxes in a soulslike
I created Hitbox and Hurtbox components
void OnTriggerEnter(Collider other) {
if (!other.TryGetComponent(out Hurtbox hurtbox))
return;
// hurtbox is now guaranteed to contain a valid Hurtbox
hurtbox.Damage(10);
}
It doesn't use physics, so no
It doesnt?
I did blockboxes in the same way, although I wound up moving away from blocking (it got more Bloodborne-y)
For the Move method no but with SimpleMove it applies gravity?
That's the whole point of it. It's a non-physics character controller
It only moves how you tell it
Forces don't act upon it without code telling it to do so.
But what about SimpleMove
This is the code I'm trying to use to transfer the velocity of the rigidbody to my Third Person Controller.
The problem is that I'm getting mixed results with the game. Sometimes the character jumps and sometimes it doesn't, neither of which matching with the velocity values I set.
Am I doing it right? Or is there something missing?
What about it
The method isn't relevant, if it's the CC doing it.. it's not physics
It applies gravity
my game does not have separate hitboxes. I have a main collider, ObjCollision component, and EntityData SO. ObjCollision listens to all collisions, makes a small struct with condensed info about the collision, and invokes anything listenning to it with the collision info.
I then have GenericEnemyLogic : Monobehaviour that subscribes to ObjCollision’s events, and it checks the entity data vs the masticated collision info to cause different things to happen.
It just does the math for you it isn't physics
Ooh okay then
So basically CharcterController provides the control of your character only considering collisions and won´t move in any direction(including vertical) unless the code you write says so
like, EntityData has an enum Cardinal for directions where an enemy can hurt/be hurt by the player, is flammable, can set things on fire, etc. And this gets parsed
eg goomba can hurt mario if touched by left/down/right, but is hurt by mario from above.
this allows different flags to be easily added to the game for vulnerability to different things
want to add radiation? just add a bool to EntityData
hi, faced a strange issue, turning animation works on pc, but not on mobile (or simulator in editor), move tree works perfectly, why is that?
this info is directed more at Fen
First of all it looks like your currentSwingable variable should definitely be of type rigidbody instead of whatever it currently is because you just keep getComponenting it.
Second, this code doesn't seem to have anything to do with jumping or any rigidbodies on this object. You're setting the velocity of a custom script that we have no information on.
oh yeah, and I wound up having something similar too
It does not make transition at all
the hurtboxes themselves just told the entity "hey you got hit"
the transition into RightTurn?
show us the transition's inspector
Have you checked if isRot is being set to true?
If not, you have a scripting problem
You can look at the animator window while the game is running in the simulator
i might need to upgrade my struct to contain the specific colliders that collided, idk. But most of my logic rn is handles via non-trigger colliders
just make sure you have the animator's object selected
i dont, it works perfectly with the same on pc
That does not answer my question.
I asked if isRot is being set to true when the problem occurs. You need to check that.
Perhaps your code isn't handling mobile input correctly.
yes just checked idk why but it doesn't change
Okay, so you have a code problem.
Look at the code that's responsible for setting that boolean
You can check if it's running at all with Debug.Log.
Looks quiet strange, cause mobile input on pc works fine also
it works fine except for making you turn :p
you aren't going to fix this by explaining to me how it couldn't possibly be broken!
get to debugging -- check if the code is running at all, and if it's producing the values you expect
i might have a nasty refactor ahead of me. My main level editor (which I made at start of development) handles level editor input, undo/redo history, preview management, and actually editting my level.
The biggest challenge is separating level editting methods between: 1) private methods only level editor has, 2) methods that only other level build classes get access to, and 3) public methods all scripts get access to.
Any recommendations?
are you trying to break this off into an assembly?
i wanted to, but it’s too coupled
I would start by finding every public member and seeing if it can be made less visible without any other changes
right now, everything that is public should be public, and everything that is private is a mix of functions that should be private and others that should only be visible to other classes in my build system
part of why i have the too-many-responsibilities problem is that I really want to avoid exposing several methods to all my scripts, which is why I kept piling on the private methods into one class
but now, I want to add more features to the level editor, and if I add more private methods to that class, I will go insane
One option is to use partial classes to break one very large definition up into multiple pieces. I'm not a huge fan of this, though.
I tried it once and wound up five files with no clear organization
that doesn’t feel like a solution
(i wound up just obliterating the entire class with a total rewrite)
gimme an example of a feature you're adding
that feels like a way to end up with one class over multiple files
yeah, that's the premise :p
level editor right now has methods:
-DrawCommand (what to do when user issues a command to draw at current pos, including validation logic)
-DrawWithLog (try to draw a tile while logging everything to the undo history)
-public ForceDrawAt (during runtime, other scripts can request drawing at a specific spot)
-public SmartDrawRuntime (force draw, but also funnels logic through some singletons that may need to update internals)
-DrawAtRegion (actually erases anything that conflicts in different tilemaps, and draws)
-SetTileAt (draw the tile, but I have special info to also manage)
these aren’t the actual names, but the actual desired function of each
If you can build up a good "core" of functions for manipulating the level, you can move implementation of the level editing tools into other classes
now I want to add custom draw logic, where certain types of tiles will have custom draw functions, where when used, they will change the map while in editor mode
imagine placing the goal flag, and the goal flag needs to move a gameobject, AND erase some tiles that would conflict with the game object, AND log all of this to the undo log
Lol it doesn't debugs at all, seems like there is no IK pass on mobile
Because i change this value probably in OnAnimatorIK
but I want to keep anything that alters the build history (for undo) under extremely tight lock-and-key
and its ok on pc but idk somehow on mobile it does not work
Can anyone please help me with what this error message means?
but my displacement works
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
show your code. i don't know what you're doing.
You can't modify a single axes of scale. Give it a new Vector3 with the new scale.
I would not expect OnAnimatorIK to not run on mobile.
and I have several sets of methods like this for rotate, erase, and I later want to add select + copy-paste. All of this needs access to change build log
in short, the Vector3 type is not shareable, and transform.localScale returns a copy of the local scale of the transform
modifying it would do nothing at all
but if I keep doing all this stuff as private in one class, it is just totally out of control, and i need to put my foot down
hence the error, and hence the fix -- store it in a variable, modify that variable, and assign the variable back
what is the difference between using raycast and onmousedown in 2d? is one better than the other?
https://hatebin.com/elnoihrfhu
Idk why but it doesnt add X force..
Line 322
i failed to split last time I tried, but I’m willing to give it another whirl.
i tried fixing it myself but nothing helped
OnMouseDown directly tells you when you click on an object with a collider on it.
it works on both 2D and 3D colliders
Physics.Raycast only cares about 3D colliders. It's useful for figuring out what object is "under" a pixel on the screen
like for shooting a gun
It ignores 2D colliders.
The closest analogue for 2D physics is this guy: https://docs.unity3d.com/ScriptReference/Physics2D.OverlapPoint.html
It lets you ask if there's a collider at a specific point
oh ok, thanks 👍
Physics2D.Raycast: Hi
this is in the context of OnMouseDown, which tells you which game object you clicked on
In the video, it looks like you're just trying to dash when jumping. Your code doesn't let you dash when you're not grounded
so I'm thinking about ways to detect a collider under your mouse
nah, i does, i fixed it
Jump and Dash have different jumpSpeed
Then share the most up to date code so you don't waste our time ¯_(ツ)_/¯
IT ACTUALLY FIXED
raycast combined with an interface is the best solution right? best performance and everything.
I mean, i didnt fixed code after uploading it
you use a Raycast in 3D because you need to detect every collider along a line; if you're using 2D physics, you only need to sample a single point in space
it'd be plenty useful if you wanted to shoot a 2D gun :p
that would be the only real use case, ig
Now, if you actually made a first person 2D game, you would use Physics2D.Raycast
But your screen would also be an infinitely thin 1D line..
not exactly a great experience
Flatland: The Video Game
Casting a whole 2D collider is just so cheap relative to the amount of information it gives, you want to actually very specifically want to shoot a thin beam for raycast to be the right one
ah ok, am i right if it was 3d though?
Yeah. In that case, you need to sample a whole line
Unless you were a four-dimensional being playing the game on a three-dimensional display. Then you'd just sample a single point in space again.
raycasting to detect ground, walls, enemies, etc in 2D is just mostly inferior to Casting collider
😁
so many people just do like a fan of raycast beams, spaced at different points. it’s actually worse than just doing the whole collider
when you have a simple shape in 2D
I do that when I actually need lots of individual samples
like if I need an enemy to be able to partially see you
i feel like there is a smarter way to do that with LineCast and Cast
anyway, point being, Collider2D.Cast is good. use it
feels expensive. is not super expensive
Sorry for being rude btw
why is raycast2d bad if you want to get the object you're clicking on?
I hope he's not using Raycast3D in 2d💀
I'm doing player movement and I applied rigidbody to this but when I move the whole character fall down logickly
How can I fix it?
you'll want to freeze rotation in the X and Z axes
you can do that from the "Constraints" section of the rigidbody's inspector
Ok thanks
I figured out whats wrong
movement makes X velocity limeted/static
And when i add X force to dash it just ignores it
cuz velocity always equal move * speed
and idk what to do, if i equal it to velocity.x it will just stay/wont move
if i remove that like character wont move
Why is it not working?
Read the error message.
💀
Man I'm beggining with 3d
Read the error message.
yeah
You can't possibly fix this unless you read the error message.