#💻┃code-beginner
1 messages · Page 259 of 1
wdym by this
why is Text not a prefab
components need to live on a gameobject
the text that pops, instead of moving this again and again i want this to be cloned every time a player clicks the piece
yeah just make a prefab out of it and Instantiate it
instantiate where in a script?
instead of doing this
TextPop textPop = FindObjectOfType<TextPop>();
MoneyManager moneyManager = FindObjectOfType<MoneyManager>();
TextPop textPop = Instantiate(etc.
yes, but now wait
because
the piece where this script you mentioned is
is a prefab and is instantiated from another script PieceSpawner
thats not the TextObject ?
and it will be impossible to just say public text textpop cause i cant asign the text to it since its a prefab
you would need to make a custom utility app yourself
idk how to describe it
ok
assign the whole prefab to the field
if the textobject is already a prefab it should have no problem being added into another prefab
oh okay didnt know that let me try
only thing wont work is Prefab -> SceneObject
the rule is that assets can't reference scene objects
(and scene objects can't reference objects in other scenes)
cause they're actual assets and they live in the Project folder (unlike gameobjects in the scene which are data inside a YAML of Scene asset file)
well, the prefabs are also just a blob of YAML :p
sometimes I open asset files to manually edit them
true true never opened prefabs, had a feeling they would be
probably not worth the effort lol
Unity used to have this thing already built in but removed it
because ur spawning it as Text not as whatever the script that contains Pop method is
computer has no idea what Pop inside Text is
You should just reference it as a TextPop directly.
lol thats backwards
give TextPop a field that references its Text component
then you can easily do...
var instance = Instantiate(prefab);
instance.text.text = "whatever";
instance.Pop(screenPosition);
what is a var?
var is a keyword that lets you omit a type name when creating a variable.
TextPop instance = Instantiate(prefab);
This will have the same outcome.
(and make it more obvious what instance is here, since prefab isn't a great name)
so wait first i did
public Text popText;
then
var clonedPopText = Instantiate(popText);
clonedPopText.GetComponent<TextPop>().Pop(screenPosition);```
why you doing it this way lol
idk, how to do this then
store the Text inside TextPop
then
[SerializeField] private TextPop textPopPrefab ;
var textPopInstance = Instantiate(textPopPrefab, etc..
textPopInstance .textField.text = "something"
textPopInstance.Pop(etc..```
ofc make sure you have a field inside TextPop for public Text textField and assigned
then why did you initially reference it as Text lol
look at what I wrote and compare it to what you wrote.
why is Instantiate the method inside TextPop ?
we both sent you examples of same thing , none had .Instantiate lol
you said to do the instantiate inside textpop
where?
idk i understood it like that 😭
store the Text inside TextPop
whats wrong with this then?
ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
sure
but then i would have to make two variables? one for textpop script and another for text object i want to position
TextPop is the whole object no? you're positioning the same thing
they're both the same transform gameObject
but doing var clonedTextPop = Instantiate(popText); is just like instantiating a script
Instantiating a component instantiates the entire game object it's attached to.
you're cloning the prefab
oh well then
which is a template to a gameobject
whats this now?
thats unity editor taking a poo
oh okay haha
the view/layout got lost somewhere
well is rectTransform assigned
is this inside TextPop?
Start runs the frame after instantiation.
yes
It's too late.
why do you have another field called textPop inside TextPop
and yes, why do you have it referencing another TextPop..?
oh i just forgot to remove this from my previous mistakes
stop and read what's been suggested again
keep the serialize field on RectTransform, and assign it already on the prefab
true you're not even using anchored pos
there's nothing special about setting .position on a RectTransform vs. on the same thing referenced as a Transform
the poptext is now cloning but not really showing in game
yeah cause you need to reference the Canvas and spawn them inside of it as child
text wont show outside a canvas
ohhhhhhhhhhhhh well
just pass it as second argument in Instantiate
var clonedTextPop = Instantiate(popText, canvasReference);
ohh you have an issue though where you need to Get this canvas now like the money script, because you put instantiate inside the falling object which is prefab (cannot assign field in inspector for Canvas)
Yo @rich adder sorry bro u gotta teach a lil bit more bc I still didnt get what you meant by your previous answer to me. I just want to know how to get the coordinate position of a gameobject thats inside a prefab. For example. The gameobject room1 B is placed in a position on the prefab and when the prefab is instantiated I want to be able to get that coordinate position and use it within another script. Still learning so sorry for wasting ur time
make public Transform fields for each Room on a script inside room prefab object
then access them when you spawn as that
demon disguised as angel 😈
Is there a good method for making something move towards a target vector, but with slippery momentum? (I.E, it overshoots slightly, and slides around with momentum)
I've got LeanTween, but that doesn't allow for continuous movement, only looping animations with set lengths.
nvm im back
yes
when I load to a different scene and back to the one where the DDOL singleton is in, I end up with 2 of the same singleton - any idea what I might be doing wrong?
I want my UI elements to move towards my mouse, but in a slippery way.
Or other locations
Loll you help the rich and steal from the poor
so whats the solution to it?
couple of different ways, each with its own pro and con
easiest (more expensive way)
is how you are doing it now with the Money script
You want something like https://www.youtube.com/watch?v=KPoeNZZ6H4s
It looks like someone went ahead and implemented the ideas (and extended them to Quaternions!) here https://www.reddit.com/r/Unity3D/comments/w001nq/i_feature_creeped_the_heck_out_of_t3ssel8rs/
then you did not make it a singleton 😛
Second order dynamics let you "follow" a target value in a way that has momentum.
is this not it?
ohhh
a destroyed SceneManagerScript, but duplicate game objects
that sentence is a mess
you have destroyed the SceneManagerScript, but you still have a duplicate game object
there we go
so instead of "this" do gameObject?
sure
yes, that will destroy the entire object
is there anyone that did spriterenderer rule tile before?
basically a ruletile but for gameobjects
Christ, that's disheartening. This is way too advanced. I can't even understand what he's saying.
and how exactly to do that with canvas? i only know how to find a script like that
hey, I mostly copied the code when I implemented it :p
well the method name gives away how you use it FindObjectOfType
<Canvas> is an objecttype
https://gdl.space/uhimomanet.cpp
Here's my own implementation.
Add a SecondOrderDynamicsFloat or SecondOrderDynamicsVector3 field to a class. Call Setup() on it once, then call Update() on it every frame. Pass it Time.deltaTime for the t argument and the target value for the x argument.
The three parameters -- f, z, and r -- are described in the video.
I should set up a little visualizer like he has in the video.
and what if there are few canvas?
sorry for the out of nowhere reply. Turns out you just need to multiply the quartenion by the vector3 (in that order) and the output will be what I was looking for.
I'm not even seeing where the code is. He's just purely explaining the college-level math itself.
Good question, you need either a tag check or put a script on a particular one and just find that script instead
alternative is to do this properly by spawning these sprites from a scene object so you can plug the references directly
alr thanks you so much
Most of the video just discusses the math and how you use it.
You should watch it to understand the meaning of those three parameters.
I am watching it, I just don't comprehend it in the slightest.
i can't do a lot for you if you just say "I understand none of this"
seems like it works 🙂
i linked you to someone else's implementation, as well as my own, so perhaps you can try using those.
note that if you're fine with not having overshooting, Mathf.SmoothDamp / Vector3.SmoothDamp will give you movement with some momentum
Yeah, I've used those in the past.
are they spawning ontop or they just staying scattered?
I've used those, but I'm aiming ideally for UI elements that are sort of "bouncy" and "slippery", which aren't provided by those.
btw Destroy has a float variable for time till destroy
i just didnt set up animation and destroy function
That's exactly what I used my SecondOrderDynamicsFloat class for 😉
then it looks like I'm using yours, 🤡 My tiny, weak brain thanks you.
it's used to make the Q and E buttons bounce in this video
why is that animator controller empty and i cannot add an animation to it?
is tehre a problem if I call a Method in Update?
depends which one
ur dragging the clips into it ?
basically I am registering the direction vector from an InputManager and passing it onto the character movement script every frame
should be fine
I sure hope not
yeah when i drag an anim it doesnt appear
Do whatever you want in Update.
I was thinking you had like GetComponent or FindObject which is kinda heavy to do every frame
even those are very very fast
those are bad because they give you brittle code
they're still slower than the better alternatives, of course
hmm maybe i was thinking GameObject.Find
im gonna reopen unity
it's still fast! just...less fast
you can do it many times per frame and your game won't blow up
oh yeah for sure wont blow up just bad habit no?
it's bad because it makes your game fall over and explode when you fix a typo in something's name
oh always thought it used reflection / scanned all scene objects thats slow
worked!
If I were to write,
//then
jsonUtility.fromJson<BotObjectSerializable>(aBotObjectSerializableJSON)
would it be able to handle the list<int> s inside the class?
It is scanning all scene objects, yes
bugggy!
But computers are still fast.
I'm just pointing out that calling Find a couple dozen times per frame isn't going to tank your framerate
it's not some massively evil bugbear
I struggle to know what JsonUtility can handle
it should
That looks fine.
but it can't handle dictionaries, right?
Rule of thumb: If it serializes in the inspector, it should serialize in JsonUtility (with some exceptions, I guess)
you can't serialize a single float, for example
Correct.
oh that's a very helpful way to put it, thank you
use Json.net 😛
wait, so JsonUtility.ToJson(0.0f) wouldn't work?
I believe not.
(even though that's valid JSON)
most people think of JSON as being at least an object or an array
but it can absolutely just be a number or a string
that's very helpful to know
I feel like one time I tried but when i imported it it had errrors 😭
did you get the one from package manager? never had any issues
probably not, I think I tried via the github
it was awhile ago
Def give it a try again from package manager at some point, its a solid plugin
the only thing it doesn't like is Vector3 but there is a workaround
I'm already kind of used to JSON Utility- what are the differences?
without going into the small intricacies, the serializing of dictionaries alone is worth it for me
It's extremely extensible. I use a custom converter to serialize objects by a GUID, and to then look them up by GUID when deserializing
that would make things way nicer. does it work with custom classes
Note that dictionaries are still a bit limited out of the box.
works with classes / struct you name it
JSON object names are strings.
I think I was having problems with serializing dictionaries, but im so used to just breaking everything down into lists and reconstructing the dictionaries anyway (at startup)
They can't be an arbitrary JSON value (like the value is)
Oh like it stores as string you mean
Yes.
I guess it can handle turning that string back into a few other types, like integers
I forget
so Deserialize doing all the magic
ive been just sticking to utility lately just because it's like the right amount of serialization I need
and more that it lines up with what I can serialize in the editor anyway
i briefly played with writing a custom converter for dictionaries
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = JObject.Load(reader);
IDictionary<K, V> dict = (IDictionary<K, V>) existingValue ?? new Dictionary<K, V>();
foreach (var prop in obj.Properties())
{
IdentifiableRegistry.TryGet(typeof(K), new Guid(prop.Name), out var result);
dict[result as K] = (V) prop.Value.ToObject(typeof(V));
}
return dict;
}
i don't enjoy reading this code
I just wound up serializing lots of pairs of keys and values anyway
🤔 should work out of the box with Newtonsoft.
(that's my own Guid class, not System.Guid)
with complex types for keys
not just a string
notably, in this case, I was serializing a dictionary whose keys were scriptable objects
json.net has a hard time anything unity tbh
vector3 gives it a self-intersecting loop issue
so I had to turn the string value from the JSON into a guid, and then use that guid to look up the correct object to populate the resulting dicionary with
There was some Newtonsoft repo that handles a lot of unity types.
https://github.com/applejag/Newtonsoft.Json-for-Unity I think it was this but not on pc atm
i remember i had to pass some options but fixed it so i moved on it was non-issue for me
I use custom struct for V3 though because the one on Unity cloud has json.net without that option so you get same error during serialization
after i reopened unity this magically stoped working
{
MoneyManager moneyManager = FindObjectOfType<MoneyManager>();
if (moneyManager != null)
{
moneyManager.AddMoney(5);
}
Canvas textPopCanvas = FindObjectOfType<Canvas>();
if(textPopCanvas.tag == "TextPopCanvas")
{
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
var clonedTextPop = Instantiate(popText, textPopCanvas.transform);
clonedTextPop.Pop(screenPosition);
Destroy(gameObject);
}
}
its giving me money but not destroying the object or popping the text
If you have more than one Canvas in your scene, the exact object found by FindObjectOfType will depend on the order the canvases were created it
which can vary after a restart
consider just finding an object by tag and then getting a Canvas from it
could also make a script TextCanvas placed on that canvas, and find that
yeah ima do this
can JsonUtility handle list<list<int>>
No, because Unity can't serialize a list of lists
You have to create a bit of indirection
List<MyStruct> where MyStruct contains a List<int>
This is a situation where Json.NET is strictly better
Correct.
I can't find it in package manager
you have to add it by name
https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@latest
com.unity.nuget.newtonsoft-json
How can I adjust the gravity of my game, because I have this problem: ¿why in one project objects fall slow and in other fall faster?
Both have the same rigidbody stats
that's probably down to the scale of your game
if everything is large and the camera is zoomed out, things will appear to fall slowly
ah, ok, thank you!
I think it isnt that because in both projects cvamera have the same settings
In both cases camera isnt changed
it is the default camera
so why does in one project fall fast and in other slow?
why its red? first time using switch
Does it give you any hints when you hover over the red squiggle with your mouse?
oh just break;
I'm not sure if Visual Studio highlights it as an error, but you might need to put break
Yep : )
hovering over the error should tell you, and it should appear in the IDE console . . .
why with Unity new inputsystem my object falls slow with rigidbody?
where'd you get that code from?
wrote it 
Unity won't know what you mean by "LeftShift".press() because "LeftShift" is just a string. You could try Input.GetKey(KeyCode.LeftShift) instead to check whether or not the left shift key is being pressed.
did you check to make sure that exists before using it?
ah, i used a string extension
public void Pop(Vector2 screenPos, int value)
{
transform.position = screenPos;
if (value > 0)
{
textComponent.text = "$" + value.ToString();
} else
{
value = -value;
textComponent.text = "-$"+ value.ToString();
}
}```
it gives me NullReferenceException, did i do something wrong when trying to get text component?
you should look up how to check for input to get information for how to access keys . . .
you should show the error message and/or tell us where (what line) the null ref error is at . . .
NullReferenceException: Object reference not set to an instance of an object
TextPop.Pop (UnityEngine.Vector2 screenPos, System.Int32 value) (at Assets/Scripts/TextPop.cs:16)
PieceManager.OnMouseDown () (at Assets/Scripts/PieceManager.cs:55)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
which is line 16?
textComponent.text = "$" + value.ToString();
okay, good. do you know what a reference variable is?
no
why when i put a custom Vector2 in rigidbody2D my object falls slow?
how do you change the volume of an audio source? ive tried audioSource.volume but that doesn't seem to do anything
Does that custom vector3 include setting the vertical velocity to 0
i would start with that. it's very important to know what a reference type and a value type are . . .
yes but it still falls
alr but how to fix it
show the code. that should work. make sure it's the correct audio source . . .
ah, nvm
Well yeah because you're setting it to 0 and then getting one frame of gravity before you zero it out again
first, you find the reference variable, then you check if it has been assigned . . .
what could be a solution
Say I have a script (UIController) and a different script that inherits from it (MainMenu : UIController) and I have a serialized field within UIController that I do NOT want to appear in the inspector for Main Menu. Is there a way to make that happen?
Don't set the vertical velocity to 0
Keep it what it is
i made sure, it worked with AudioListener.volume but audioSource.volume doesn't change it at all https://gdl.space/ibeyekasoc.cs
@queen adder there are only two variables on that line. can you at least tell what the two variables are?
ive looked at that and didnt work for me
It is a vector I get from an InputManager of Unity new Input
Guys I have this thingy where it is a model with a shape key where the sides are pushed away between then, mantaining their shape. This is so I can make several of these with variable sizes with ease when importing them. I want then to be a single entity cause I want them to behave entirely like one (like be isntantiated togheter, share health and stuff). But I am actually wondering for a while... How can I make so the colliders fit any possible distance this shape may have? Cause I need the middle one to be a different type of collider than the other two.... Could I calculate something about that with code or should I try something different entirely?
Then you're changing the volume of the wrong audio source
is there any way to change it?
im not, musicSource is the correct one i double checked
okay i fixed it with GetComponent<Text>().text = "-$"+ value.ToString();
where in unity docs did they tell that KeyCode.LeftShift is "left shift"

Velocity does not come from input, it comes from the rigidbody. Don't change the y value of the velocity
Show code
your textComponent variable is not assigned. use GetComponent to assign the Text component to it. you don't want to use GetComponent<Text>().text every time you call the method . . .
I cant access the x component of the rigidbody velocity
Try logging the volume before you play it
can you log the value of volume before and after it's changed?
i have assigned it to text in the inspector
Rigidbody doesnt have an x value. Velocity does
but I cant modify it
then check for a duplicate script . . .
i just realised what it is
i changed the method name which means its missing from the volume slider
You cannot get and set an individual component of a vector in the same line. You need to set the velocity to a new vector
would json.net be able to handle this?
or do i need to unpack
Okay, Thanks!
I dunno about using Vector2 as a key.
but you can always try it and see (:
Is there any way I could convince you to help me out a bit with your script? I'm trying to figure out which order the functions in it want to be run for it to function on an object, since it's not a monobehavior and i have to implement whatever it's doing in my own script..
you set it up once, then update it constantly
the Position property gives you the current value
If you know your velocity, you can also pass it as a third argument to Update. If you don't, it'll just calculate a velocity based on how much x has changed since the last update
ahh, thank you. Sorry about missing that. Thank you very much for the help. I might be able to muddle my way through to understanding this, but not without an actual example to experiment on and observe.
The video describes how those three parameters work
Roughly speaking, f is the frequency of oscillation, z is the damping, and r is how much it “winds up” before moving to the target
Hello, I'm trying to make an online multiplayer platformer game, just doing the basics as of now. I have a player, and a moving platform. I want the player to move with the platform while standing on it. I tried making the platform the player's parent, but the player doesn't move with the platform still. (the player stays in the same place but it's local coordinates change, indicating that it's moving relative to it's parent.) How should I be doing this?
Show script. We can't just guess what's wrong.
so I've got a method on a button that is returning an object twice for some unknown reason - debugger (I dunno if I'm watching the right things even) just confirms that once the method has run it returns to the start of the method (or at least the break-point I created). Debug log returns everything as in proper working order except for the returning object, which gets two rank increases instead of one. Code not shown because I can't figure out the Pastebin quicklink...
how does one find the Pastebin/Hastebin quicklinks?
does any one know why my random range is only returning 1?
private float Spread()
{
int random = Random.Range(1, 2);
if (random == 1 && _playerMovementScript._isWalking == true) /*return +_bulletSpreadWalk*/ Debug.Log("1w");
if (random == 2 && _playerMovementScript._isWalking == true) /*return -_bulletSpreadWalk;*/ Debug.Log("2w");
if (random == 1 && _playerMovementScript._isSprinting == true) /*return +_bulletSpreadSprint*/ Debug.Log("1S");
if (random == 2 && _playerMovementScript._isSprinting == true) /*return -_bulletSpreadSprint*/ Debug.Log("2S");
return 0;
}```
!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.
I just found it thanks
Range is exclusive
You are essentially saying "give me a number between 1 and 1"
wait, no
It should still give a float?
i have a min of 1 and a max of 2 ?
https://hastebin.com/share/lidiyuquge.kotlin
the culprit in question has something to do with line 11
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yeah, I got confused with the c# one
for ints, the max range is exclusive, meaning, it is not used. so your range is from 1 to 1 . . .
Oh then I was right
Try rounding the value before it gets converted to an integer. Edit: You can use a max of 3 and avoid the rounding.
so should my min be 0?
The max should be 3
i dunno, what values do you want to choose from? just add 1 to your max if you want to choose between 1 and 2 . . .
Either way, if you want a 50/50 chance, I'd go with floats and (0f, 1f) honestly
The movement script for the player, and the triggers for the moving platform, and how to platform moves:
And what is the problem again?
!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.
The platform becomes the parent of the player correctly, but when the platform moves, the player doesn't move with it
You're setting the player to be the parent of the platform, no?
No I'm setting the platform to be the parent, so that the player becomes the child and moves with the platform
Ah, I see.
Could you try using SetParent?
If I'm not mistaken, SetParent (with false as second parameter) would force the child to move next to the parent
Are you sure the OnTriggerEnter is being called? Do you have isTrigger enabled?
I tried just now, but when the player landed on the platform it teleported far away
@swift crag I've finally gotten it working, and the sheer relief and excitement I feel is palpable. Thank you so much for your help and code. It looks so great!
I really can't thank you enough
Yes the player becomes the child of the platform when it's standing on it
What happens if you set the parameter to true?
And you have isTrigger enabled on the platforms collider?
It is running the code inside, so that is not the issue apparently
And this is weird. SetParent(object, false) should put the object next to the parent
I just tried SetParent with the parameter set to true, and it's back to how it was. But I'm noticing there is like a very subtle movement but it's a bit jittery, but it's moving only a few pixels
This is a dynamic rigidbody, right?
Yes I have 2 colliders on it actually (idk if it's good or bad) one for the player to stay on, one for the trigger
the platform?
It's perfectly fine to have two
No, the player
Yes the player has a rigidbody that is not kinematic (if that is what you are asking)
If so, its position is not gonna move with the platform properly
Yeah, that is what I'm asking. Non-kinematic means dynamic
so when the player is on the platform I should change it's rigidbody to kinematic?
You could try that. Or you could just actively use the platforms movement in the velocity calculation
So making the player's rigidbody kinematic when it's on the platform works! but now I can't move the player 😄 maybe I should change the player controls and not use velocity overall?
ugh, this is doing my head in
I'm claiming a mental health day...
Thanks for clearing that up, that just confused be for a sec
i have a prefab that has a script component but sometimes i wanna spawn in a version of this prefab wothout that specific component is there a way to do that?
currently i tried this and it doesnt seem to work
have you tried a RemoveComponent yet?
is there even a thing?
Destroying the component should work fine. What goes wrong?
hmm i was afraid that the problem was going to be something else, but i expected that.
well you see, what decides if a projectile can be parried or not, is this script: https://gdl.space/jenivasexi.cpp
And once it decides that, it gets painted red, thats how the player knows they can parry.
Problem with the bomb projectile, is that it can split into 2 smaller bombs, but for some reason, whether they are parryable or not (red or not) is ALWAYS dependant if the bomb they "split" from is parryable or not. but i dont want smaller bombs to be parryable, ever.
I assume this code of the parryable script should not be like this, maybe this changed something that shouldnt be changed
Destruction isn't instant.
It happens at the end of the frame, iirc
or maybe on the next frame?
It sounds like that Start method is executing before the component dies.
Verify that with a log
log both in Start and in OnDestroy (add that method)
ye i thoguht abt that, but then why does it always depend on the "main" bomb? its a random nuimber generator that decodes if its gonna be parryable or not
but never seen a smaller bomb be parryable when the main one wise, vice verca
i'd need to see the entire bomb script
one thing -- make bombPrefab a Bomb, not a GameObject; that'll simplify your code
it'll avoid the GetComponent calls
I would check if Start is actually running on the small bombs
Well, you have a few choices.
- change to when on a platform kinematic and use MovePosition only during that time
- use kinematic always
- keep dynamic incorporate the platforms velocity into your movement calculations
There are other things too, but that is what is on my mind now
But yeah, kinematic rigidbodies can't use velocity or addforce
so debug.log in the bomb script start and in en on destroy method in the parryable script?
ah, no, both in the Parryable script
after bomb split
why did the initiation of the original bomb not debug.log("start") ?
weird
I have an issue where if an enemy leaves the tower's targetingRange before it fires a shot, it changes to the next enemy in the array, often not able to hit that enemy before they leave the targetingRange - causing the tower to be basically stunlocked and not doing anything. What could I change in this code to fix that? https://gdl.space/qotomiqiki.cs
isn't that the first log entry?
the first bomb's Parryable logs start and destroy
the small bombs both log destroy
Should the tower be a ble to shoot at an enemy that has left its targeting range?
No, I guess the best middle ground would be to complete the shot in the direction it is facing but I feel like that would cause a set of issues of its own
if you're talking about an enemy moving out of the range making the projectile target the next target in range:
You should tell the individual projectile to target whatever you shot at, don't let the tower give that information.
also, JESUS, use vectors instead of four cases for each direction hahah
lol probably right I'm just glad it works
fair enough.
Can you be more specific with the issue?
From what I understand, it breaks when a character that you shot at walks out of the targeting range after you've shot.
I don't see why this breaks it though...
I think the issue is with the else {target = null} as its causing it to essentially reset the shot?
so it doesn't complete the shot on the tower that left its range
and then it starts a new shot on the next tower thats in range
right, I can see it.
uhh, so currently the tower handles the shooting and the projectile itself right?
yes, if the projectile loses its target (if target was destroyed) it just keeps moving in the direction it was fired in
the issue seems to be with the towers themselves
right, okay. So the tower just shoots the last bullet that then travel in the general direction of where the enemy left the range?
After this the tower just gives up?
it essentially gives up if enemies leave its range before its finished its shot
finished its shot? Meaning finished charging it up, or just when it hits an enemy?
charging it up
well, FindTarget() should take care of it no?
it's not like the amount of targets are empty right?
FindTargetAerial and FindTarget check different sorting layers I believe
different towers can target different sorting layers
layermask* i meann
ah, makes sense.
In this case it does find more targets though right?
set your inspector to debug mode and you can see what the current target is.
it should yes, but i feel like this will just do the same thing it was doing earlier
yeah. If it doesn't have a target at all, that behaviour would make sense right?
if it does have a target, we know that's not the issue
then it's something about getting stuck in the charging process.
right-click the inspector window
and select Debug
to see private variables
check if the target is null when the tower is wonky
Anyone know any good torurials
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
do I share code on hastebin or pastebin, I forgot which one is the bootleg
nvm looks like pastebin has better reviews, so it looks like the right one
I recommend gdl.space, then hastebin, then hatebin
gdl.space i like how spartan it is
only what you need with good colors out of the box nothing extra
ah, thanks
I have this big class, which I'd like to split into smaller classes
https://gdl.space/wunusafuni.cpp
the problem is that is has a constructor, and I'm unsure how to split my code when it has a constructor
(I'd like to move the CreateVertexBufferCS method to a different class for example)
you can chain constructors
2 constructor
On a quick look, that is all a single purpose, and is quite short
Where do you want it split? oh, missed the last sentence, nm
but also think i would just use composition
haven't heard of composition before, I'll look into that
like you mention a method
do you want all data it touches moved as well?
if not i would just leave it
not necessarily moved, but just accessible from the child class
im having a issue with this movement script ```public class Movement : MonoBehaviour
{
public float speed;
void Update()
{
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * speed);
}
else if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * speed);
}
else if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector2.down * speed);
}
else if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector2.up * speed);
}
}
}``` im having a issue where if my framerate goes down a decent bit the movement looks really choppy and not smooth at all is there any way to fix it
why cant the child access it
dont see a problem here (oh yeah forgot deltatime there if you're moving directly by transform whoops)
well I'm getting this error when I try to inherit, and it's due to the parent's constructor
Multiply by deltaTime in those translate calls
given the current code i would not worry about it since its already so short. but if you wnat just define a new constructor that chains to the old one
public NewMeshData(args) : base(args) {
it's gonna get really long, I'm in the middle of refactoring something actually
I just shortened it down for the example
overriding constructor or making another new one in the child, no?
it's like a 1000 lines long
i would never split things due to the size of the code, only for splitting the functinality
probably more, since I have to include the fallback for devices that don't support compute shaders
but also you can just define a new constructor on the extending class
it just has to call the previous one via the syntax i showed above
or just put the stuff in its own class, and make that a member of the main class
if (Holding)
{
TargetDirection = TargetPoint.position - Grabbed.position;
Grabbed.transform.GetComponent<Rigidbody>().AddForce(TargetDirection * 2f, ForceMode.Acceleration);
}
How do I get the grabbed object to get exactly to the target point.
Do you want it to stop at the target point? If so that will be some nasty calculations, depending on what movement it is
Alternatively you can use a tween animation to the target 😄
using a vector and inputs here would be a lot easier.
there's plenty of tutorials for movement in 2D, I'd recommend watching one or two!
i also want it to be physics based
Well you can make it have velocity in the direciton of the target point and slow the velocity based on distance
it can still effect other things if you use MovePosition on the rigidbody
but otherwise i would directly take control over velocity
so i can slow it down as it approaches
physics based grabbing is quite difficult to implement, but you're on the right track here. Things like dampening though is quite a pain in the ass to code.
I'd suggest creating a joint between the object you want to grab and the grabbing-point. This way you let Unity handle the physics themselves after some tweaking.
things like rotation can also be handled with a "character joint", but it requires a lot of fiddling to get correct behaviour (speaking from experience with the damn thing)
The force would need to be calculated based on the remaining distance and current velocity
Oh im blimd
But where to go from there? If it still somehow colours them
Make the parent abstract, declare an abstract function "OnCustomTrigger(AIStats stats)" or whatever you want to name it and call that
In the child you then define the function
save it to a field, or just make it a function you call in to get it
I need help!
At line 291 of the first paste, an Empty Slot is being added to a Grid Layout Group, and then, an inventory icon is spawned, and that empty slot is set as a target for a smooth transition function.
When I use this normally, it works fine, but when I try to insert an empty into the grid layout, and set its Child Index to the correct number, it doesn't work correctly, the icon on the far end seeming to snap far away and then travel to the end slot, while the rest of the slots simply snap into their new position, without transitioning.
Note, that the Icons and Empty slots are not parented to one another, they are seperate objects, and a script is being used to make one travel towards the other.
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.
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.
Does anyone have any clue why my Insert slot function might be behaving wrong?
It's correctly setting the icon to the intended target, but visually, it's snapping in ways I'm uncertain of.
photographedGridTiles = AssetDatabase.LoadAllAssetRepresentationsAtPath("Assets/art/Grids/PhotoGrid.png");
is it possible to turn these objects into sprites? it's loading in the correct objects and the correct amount of objects but I'm not sure how to get those objects (individual sprites) into objects
yea
how can I do that
loop then do as Sprite
well i know to loop but how would it go for the object to sprite? i.e. photographedGridTiles[i].turnintosprite
Sprite.Create creates a sprite from a texture
Unless these things are ALREADY sprites
In which case you don't need to turn them into one
its a spritesheet i think
they are already sprites.
Then there's nothing to turn into anything
let me describe my problem i suppose
Use the generic forms of the functions from AssetDatabase
I have a spritesheet sliced into 300 sprites and want to load these in programmatically.
the Resources.LoadAll is giving me issues
Use this
do Object[] data = AssetDatabase.LoadAllAssetsAtPath
typecast like this?
(Sprite)photographedGridTiles[i];
it did the same thing (I believe made them objects rather than sprites, but also imported the image itself and put 7 there for some reason
Wdym "it did"? Show your code
Loop through and only take the Sprites
The asset file is going to contain the texture as well as the Sprites
So, in the function at 291, I am 99% sure that when the new icons are instantiated, changing their Sibling Index does absolutely nothing.
if(data[i] is Sprite sprite)
{
SpriteList.Add(sprite);
}```
And I'm not sure how to force them to obey the hierarchy.
photographedGridTiles = AssetDatabase.LoadAllAssetsAtPath("Assets/art/Grids/PhotoGrid.png");
radargridTiles = AssetDatabase.LoadAllAssetsAtPath("Assets/art/Grids/PhotoGridRadar.png");
for (int photoIndex = 0; photoIndex < 300; photoIndex++)
{ tempGridObjectClass[photoIndex].radarPicture = (Sprite)radargridTiles[photoIndex];
tempGridObjectClass[photoIndex].picturedPicture = (Sprite)photographedGridTiles[photoIndex];
}
I set the sprite image programmatically later.
oh- hold on
ok it works now
thank you both
Yeah, I've done some testing, and when I instantiate an object, setting its child index in the same function does not work, the new object will still appear at the end of the hierarchy.
I'm not sure what's going wrong.
can you make a video showing issue with a small summary of issue? I cannot understand from original
Removing Items and Adding Items to the end of a list work correctly, but when I add an item to the middle of the list, it does not set the new icon's sibling index to match that of the index provided in the function.
Instead, the new instantiated icon is ALWAYS at the end of the hierarchy, even after using SetSiblingIndex on it.
even in the editor menu, I can see the new icons are being added to the end of the hierarchy, no matter what.
your inventory display could probably simpler than this
I don't know how, and that isn't exactly useful to solving this problem. I just want to spawn an object, then set its place in the hierarchy in the same function.
The inventory is working just fine, it's just that it's not correctly adding icons to the middle of the hierarchy, but instead exclusively adds them to the end.
hi guys, can we detect the collision of a child object ?
My cone is a child of the ghost, i want to detect collision of both with the player and do two different action.
The script for the ghost is in the ghost.
Assuming the parent has an rb, collision messages would be forwarded to the parent object.
Okay ty, my ghost doesn't have a rg, my player has one
If it's moving and has colliders, it should have a Rigidbody
Oh ok i've had a rb, ty
void OnTriggerEnter(Collider other)
{
Debug.Log(other.transform.IsChildOf(transform));
if (other.transform.IsChildOf(transform) && other.CompareTag("Player")) {
Debug.Log("ON GHOST");
followingPlayer = true;
playerTransform = other.transform;
followTimer = 0f;
}
// else if (other.CompareTag("Player"))
// SceneManager.LoadScene(0);
}``` I try that but my debug.log never return true 🤔
This code is checking if the object it collided with is a child of the ghost??? Why?
hello there
private void Start()
{
curLvl = UnitLevel.level.currentlevel;
UnitLevel.level = new Level(curLvl, OnLevelUp);
}
and
public Level(int level, Action OnLevUp)
{
MAX_EXP = GetXPForLevel(MAX_LEVEL);
currentlevel = level;
experience = GetXPForLevel(level);
OnLevelUp = OnLevUp;
requiredExp = CalculateRequiredExp(level);
}
and
public bool AddExp(int amount)
{
if (amount + experience < 0 || experience > MAX_EXP)
{
if (experience > MAX_EXP)
experience = MAX_EXP;
return false;
}
int oldLevel = GetLevelForXP(experience);
int nextLevel = oldLevel + 1;
experience += amount;
if(oldLevel < GetLevelForXP(experience))
{
if(currentlevel < GetLevelForXP(experience))
{
currentlevel = GetLevelForXP(experience);
if (OnLevelUp != null)
OnLevelUp.Invoke();
requiredExp = CalculateRequiredExp(currentlevel+1);
return true;
}
}
return false;
}
Problem: while there's only one hero subscribed to this, it's all okay.
As soon as 2 are subscribing = disaster.
What can I do to make this system work for many?
What does "disaster" mean?
And what do you mean by subscribed? I'm not seeing any events
If the cone (my child) detect the player i want to follow the player position, if it's the ghost who collide i want to reload the scene
That doesn't answer why your code seems to expect that the player would be a child of the ghost
Because that's what that code checks
Oh
basically as only 1 character is "online" and using it, it gains exp properly.
As soon as I use this code here:
private void Start()
{
curLvl = UnitLevel.level.currentlevel;
UnitLevel.level = new Level(curLvl, OnLevelUp);
}
``` on another, and 2 are in the game at the same time, both are getting exp, but it starts with previous value always. With the one character were loaded into the game.
LEt's say character loaded with 1300 exp and got 120 exp for the battle.
At the start of next battle exp is 1420, seems fine, till it gets exp again. Let's say he gets 50. Now after leving the battle hero will have 1350.
but why C# transform.IsChildOf(transform) return true on all collision ?
There's not nearly enough context here to answer why
I simply can't debug the problem. Just saw that while only 1 unit is using the thing, it's totally fine. As second one were enabled = it's all nuts.
This is checking if an object is a child of itself
True by technicality if you look at the docs for IsChildOf
Why can't you debug it?
I have no idea what should I debug ))
If the problem is that you're gaining too much experience or too little experience, I would start by checking when and where the code that gains experience is running and on which objects
OnLevelUp.Invoke(); Action tho?
but sounds like probably you are storing the same value in multiple places and losing track of what the "true" value is
Why are you doing OnLevelUp = OnLevUp;
can you read? I described the problem with damn numbers even. I don't get too much or too little. I don't get the exp. That's it
and where do these variables even get declared
I ahve no idea, this system is from youtube
So you don't understand the code at all, it's natural you're having trouble debugging it
Ty for your reply, im trying to find a solution for handle my 2 case
anyway this is going to raise my blood pressure right now and I should be asleep
so I shall go to sleep
I understand the code and it works just fine for 1 unit, as soo nas more appear, there's trouble. If I would damn understand the fcking problem and could debug it, I would not come here, don't you think?
Hello everybody, newbie question: Is it ok for one gameobject to have several trigger colliders of various sizes with one rigidbody. The idea is to check different things, like if gameobject is inside a zone, colliding with specific objects which have different trigger distance.
Or should I create 1 child gameobject with collider + kinematic rigidbody instead ?
If you need to differentiate between the colliding colliders, it's better to have them on separate objects with their own rbs.
what is rbs ?
rigidbody
Why is it better for them to have their own rigidbody if all those child rigidbody will have the same parameters ?
Don't you want to know which one collided?
Did I misunderstand the question?
If you have several colliders bound to one rb, they're considered a compound collider and it becomes difficult to know which of the colliders was responsible for a collision.
I see, but if I assign different colliding layers to each colliders on the same gameobejct, I'll know which one triggers, right ?
In this case, I don't need to add so many child rigidbodies, right?
I'm asking because I'd like to create a kind of moba game where soldiers need to capture points. so I'd need a collider to check waypoints, check if they are inside capture zone and a shooting collider too of course.
There are only 32 layers in total. If you're ready to sacrifice some of them just for this feature, sure.
But since I'll have many soliders, I'm worried having so many child rigidbodies might put an unecessary strain on the game
Ok thanks. I don't think I'll reach that many layers in the game so that should work. Otherwise, I'll go with child object then. Thanks for the explanation
Kinematic rbs wouldn't really affect anything that much
Ah, got it. Maybe I'm overthinking this then indeed.
Best to go with the simple solution first and test and profile as you go
But having specific layers collisions should reduce collider calculation too, right?
Hm, true.
Sure, but you can do it with the rbs too.
I'm just worried after the code becomes more complex, it'll be hassle to change
Indeed.
If the code is designed in a good way, refactoring one part shouldn't be a problem
True, Unity is quite nice to work with on this aspect.
Ok, I'll got with children then, it'll be clearer indeed. Thanks for the help.
in hlsl, how do I check if a variable is unassigned/undefined? Null doesn't work either
if (waterPointsLength != null) {
HLSL only deals with value types afaik. There's no null
okay, thanks for clarifying
you could use that
the code works but i cant find a way to make it more of an animation rather than just doing it instantly
use a coroutine i think
its a coroutine
oh then lerp the value
That while loop doesn't really add anything.
It executes completely immediately
i have tried with a for but it also makes it immediately
You need to yield inside the loop if you want it to execute over time
true
why didnt i think of that 😭
what is lerp?
interpolates between two values
Lerp on it's own doesn't solve anything. It would need to be done over time as well.
dotween lets you make a curve as well
so if you want it to start slow then speed up or visa versa its cool
i want it to be linear but i could use that for other things
omg it looks so cool now
You can have linear interpolation with dotween as well. Probably(havn't used it).
But it would be weird if they didn't have that option
yeah but that is like using a bus to go to the neighbour´s house
It could help you get rid of a lot of boilerplate code. I don't think that analogy is correct in this case. DOTween is specifically for interpolating values over time.
i havent used it nor seen it so i may be just talking shit but for what it sounds like it seems usefull for things that are a bit more complex, i just want to augment something overtime by the same value
dotween is super simple
it makes a whole couroutine function that is inefficient into one line
then i should learn it
takes like 2 minutes
imma write a reminder on that
yeah but i want to finish this since i gotta leave in a while
👍
Not saying that you should necessarily use it. Just suggesting not to discard it due to false assumptions. I for example never used it and doing just fine.
yea for sure, just super helpful
no real reason to try to reinvent the wheel i guess
im coding a script for enemies that when the raycast from a gun object its the enemy object 10 times it disapears
but with multiple enemies
no matter which one i am at
shooting at one takes the health bar down of a certain one
i have the same thing in my game ``` private void Pierce(IDamagable damagable)
{
if (numberOfHits <= pierce)
{
if (damagable != null)
{
damagable.TakeDamage(damage);
numberOfHits++;
if (numberOfHits > pierce)
{
Destroy(gameObject);
}
}
}
}```
if you want to reference it
is there something i need to do to make unity tell the difference between the enemy objects?
since it only works with one
mine is vaguely similar
the logic should be on the projectile
this function is called when it hits a collider
oh with raycasts its a bit different
You're completely ignoring the Raycast result
you need to only apply the changeHP to the first 10 enemies
Isnt it just a boolean?
it has an out
The RaycastHit
which contains all the colliders
It tells you details about what you hit
Hey, is it possible to "Capture" a Full screen
EG like Discords ScreenShare in Unity
I'm trying to make a Virtual Workspace App for VR but need to mirror the Users Screen to the Game Monitor
is this possible or do i need a different approach than Unity
you mean my hit.collider tag?
@misty coral I will look back here later
The actual object you hit is what you want to reduce hitpoints on.
Instead you're reducing hitpoints on some random other reference you have from elsewhere in the script
Think about it
maybe consider using RaycastAll
Why would they do that and how would it simplify things?
10 times
loop through the first 10 enemies returned
They're saying the enemies have 10 hitpoints
i know i know, i wasnt saying that i should learn it as a must but more as a it could be usefull
I hope we can make Resources.Load target other folders as well
Resources is waaaaaaaaaaaaaaaaay too far in the alphabet
You can target any folder you want.
As long as it's in the Resources folder
yea so i either go with one of these
either toooo far, or ugly folder chain 🥹
im kinda getting bothered by clicking 2 folders just to work on somewhere 👉 👈
Then don't user Resources at all.🤷♂️
It's not even recommended anymore
I am using Unity Editor 2023.2.3f1 and any changes in Animator during runtime will break animation
How should I handle a capture zone if the player can die on the zone but still be revive? I attached a collider on the player and one on the zone so a simple collisionenter will trigger the capture but how do I check for a stop capture easily? The player can be shot down but his collider would still be in the zone so it won't trigger the collisionexit. Would disabling the collider while dead trigger the collisionexit?
Stop capturing when the player dies, that's all
Indeed, I thought about it after. I'd need to add some code to the die function then. Thanks!
I'm still hesitating to use this solution in the end because there might be other ways for capture to be stopped and it might be hard to track everything, plus the fact that zone capture code would be split in other scripts. I'm looking at OnTriggerStay now and I'm wondering if it would be a heavy operation to add there directly ?
I guess I'll go with triggerstay first since it seems safer to use though less performant. I'll look into it further if I get performance issue in the future.
You're looking at it backwards
https://hastebin.com/share/acuritiwev.csharp
Hey guys, would anyone be able to tell me why the localRotation of my hands doesnt seem to be lerping correctly? I think the issue lies in how I'm using Quaternion.Lerp, as I am able to assign the localRotation correctly at the end of the "animation"
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The capture code should be pulled out of physics callbacks entirely and managed centrally from the zone.
you can see the rotation curve is exposed in the inspector to the right, any help is greatly appreciated ❤️
Shouldn't it be Quaternion.Slerp?
I dont think so, I tried using quaternion.slerp and it gave me the exact same result :/
rot lerp is returning values between 0 and 1
so thats not the issue
only thing I could find to be the issue is quaternion.lerp returning bogus values for some reason
idk why
Slerp is correct for rotation. Lerp is for linear motion.
I suggest adding logs to both of these functions
Make sure the binding one isn't running multiple times for example
damn I figured it out
the targrot in the scriptable object was quaternion.identity
or atleast it was exposed as (0, 0, 0) in the inspector
setting it to (1,1,1) for each of them fixed it
kinda weird but hey its fixed I cant complain lol
thank you for your time
That doesn't sound right... Something is definitely off.
I've actually experienced issues like this with my unity version before
I've no idea why but when I was making a script for hand bobbing
it would sometimes crash when trying to lerp between quaternion.identity and another quaternion
really weird but I just added a check to make sure it isn't quaternion.identity and if so change the starting/ending rotation to quaternion.euler(1,1,1)
really weird but my unity version seems to hate quaternions I have inspector issues too
How so?
But trying to implement it, you're right, my idea is wrong, that's not how triggerstay work. I was thinking it would give me all the colliders in the zone at once but it only work one by one. There would be a physics.overlap solution but that would also seem backward. I'll stick with the original die modification idea then and simply add a list of units in the zone with triggerenter and triggerexit myself rather than trying to calculate it at once.
It definitely shouldnt crash, do you mean an error was logged? I assume you mightve created an invalid quaternion somewhere. I highly HIGHLY doubt you've come across such a major bug with quaternions. If so, this would be something to report to unity
well yeah there was a null exception, pretty sure it also occurs when I lerp between quaternion.identity and quaternion.identity, instead of just returning quaternion.identity the whole thing goes kablewy
I recall identity having four values where the last would be one as zero is undefine? Did you perhaps try to move some value towards Quaternion(0, 0, 0, 0) without yielding?
Well a null exception is something else entirely. When you get these errors, you should deal with them properly instead of just glossing over them. Like google the error, or show them and ask about it. You've maybe mistaken one error for another, thus leading to you this random (1,1,1) "solution"
Pretty sure identity is still 0 0 0 1. Default is an invalid quaternion, since it is just all 0 in that case
imma keep it 💯 witchu idek what "yielding" is, and idk if this is relevant but I can't copy quaternions in the inspector, can't copy either the euler angles or quaternion it doesnt give me any prompt to copy it when I right click it
I'm on 2021.3.1f1
oh yeah sorry I dont mean like the entire editor crashes my bad lmao
you should certainly upgrade to the latest 2021.3
I'm too apprehensive about my project going kablammo lol 😭
no it wont. But backups are a thing
the early versions of ALL LTS's are very buggy and should be avoided
hi, any idea how to make methods for these anonymous functions?
i dont know what to do with @event
it said "long term support" so I just assumed that meant they would fix the bugs on that same version lmao
and updates for it would automatically install
no, Unity never updates. You need to install newer releases
Also I don't think Quaternion is your problem
this code
Quaternion q = new Quaternion(0, 0, 0, 0);
Debug.Log(q);
transform.rotation = q;
Debug.Log(transform.rotation);
produces this output
see the thing is if you look at the clip, its still able to assign the transform.localrotation to that targRot quaternion
but during quaternion.lerp it just returns bogus values
it was changing that targRot value to (1, 1, 1) in the inspector that fixed it but eh idk
yeah I learned it the hard way lmao
heyy can someone explain this bug to me real quick please?
I tried looking it up but... to no avail -.-"
What bug?
that looks like a corrupt meta file
Idk, Iv3 only ever seen this error referred to as a bug
wdym?
do you know what a meta file is?
no, sorry ^^;
never mind. Close your project. Delete the Library and Temp folders in your project. Open your project. It should clear the error but may take a while
no, but there is no way I'm going to explain the details of how Unity works in 3 sentences
Im.. gonna look it up some more
why is this happening?
how to avoid those weird unity messages? they are just being spammed
if (value > 0)
{
GetComponent<Text>().color = Color.green;
GetComponent<Text>().text = "$" + value.ToString();
} else
{
int fixedVal = Mathf.Abs(value);
Debug.Log(fixedVal);
GetComponent<Text>().color = Color.red;
GetComponent<Text>().text = "-$" + fixedVal.ToString();
}
Why the text changes to "-$" instead of "-$5"?
The debug.log says 5 as it should be
oh wait the text changes correctly but it seems like it cannot fit
...it was solved when I removed a gizmo icon from a gameobject-
So it was a corrupt meta file
I want to make a human model(That i downloaded from random site) Move Is there way to make it possible(With walking Animation)?
If i made it my self do i need To make Animation for it or i can just add velocity to diffrent parts of the body?
If you want it to look even remotely realistic, you'll have to make an animation. Adding velocity would at best make it look something like this
I made a pixelated retro effect on my game with the Render Texture Technique
the thing is, when I drag n drop my texture in PlayerCamera>TargetTexture, it shows the effet but not the UI anymore (like the crosshair, stamina...) and shows this:
how can i fix that??
(ping me if u have an answer pls)
idk what that is, but it made me smile, thanks! 😂
why isnt the class carrera apearing in the inspector?
controls.Player.Move.performed += ctx => _moveInput = ctx.ReadValue<Vector2>();
controls.Player.Move.canceled += ctx => _moveInput = Vector2.zero;
If I press A and D at the same, why is _moveInput.x equal to 0? There is no other code involved that changes the variable
Because it's not marked as [Serializable]
What else would it be?
ty
The value of the last pressed key, at least that was what I expected it to be
So if A is pressed, the value is -1, if then also D is pressed I expected it to be 1, instead of 0
The input system assumes that trying to move left and right simultaneously cancels each other out
on hardware level the terms used is SOCD cleaning
Interesting, I'll read up on it, thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootingSystem : MonoBehaviour
{
[SerializeField] private Transform StartPosition;
[SerializeField] private GameObject AOE;
[SerializeField] private PlaneCreator Ground;
[SerializeField] private bool isShooting;
private GameObject highlight;
private void Update()
{
if (Input.GetButton("Fire1"))
{
if (Input.GetButtonDown("Fire1"))
{
highlight = Instantiate(AOE, StartPosition.position,Quaternion.identity);
}
if (highlight != null)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Ground.Plane.Raycast(ray, out float enter))
{
Vector3 hitPoint = ray.GetPoint(enter);
hitPoint.y = StartPosition.position.y;
Vector3 direction = (hitPoint - StartPosition.position).normalized;
Quaternion rotation = Quaternion.LookRotation(direction);
highlight.transform.rotation = rotation;
highlight.transform.position = StartPosition.position;
}
}
}
}
}
why is the object rotating only if the cursor is far away enough from the player?
how can i add momentum to movement?
you put your left foot in, you put your right foot out
inertia
you need to implement acceleration, and not just straight sharp velocity changes
ie velocity needs to change proportional to deltaTime
okay, thanks a lot, let me try
try gizmo the exact positions you're getting from the raycast
but what if I am using in fixedUpdate
I can't see any obvious problems with the code...
Debug.DrawLine(ray.origin, hitPoint, Color.red); Debug.DrawRay(StartPosition.position, direction * 10, Color.green);
maybe throwing in some debug rays can help isolate the problem. I suspect this might have something to do with the transforms in the hierarchy and local vs world space
I'm making a system where some UI elements are alternating between being activated and deactivated repeatedly (think a blinking "warning" sign).
Obviously there are a lot of ways to repeat the same action over and over, Coroutines, using a timer, etc. But those solutions all feel somewhat dirty to me. Is there a pattern for this I'm not aware of?
coroutines are fine
Even if I just want it running forever?
yeah, that or using tasks
I think I would just make a component called 'Blinker' or something, that encapsulates all that logic (maybe even removes itself after x second). then you just add it to whatever gameobject you want to enable/disable
Anybody has a solution?
Just seems like a lot of code to do essentially
timeUntilNextBlink -= Time.deltaTime;
if(timeUntilNextBlink < 0)
//dostuff
In update
I say it is just blinking back and forth for simplicity but there is actually some logic to when it's "on" or not
The warning siren isn't constantly on
kinda the whole point is component based architecture 😄
but it depends on if you have a lot of components that need this behavior, if they need to blink at different speeds, different ttl etc, etc.
something like this, curtesy of gpt
public class BlinkBehavior : MonoBehaviour {
public float blinkInterval = 1.0f; // Time between blinks
public bool enableBlink = true; // Toggle the blink behavior on or off
public float timeToLive = -1.0f; // Time to live in seconds, negative for infinite
private float timeSinceLastBlink = 0.0f;
private float lifeTimer = 0.0f;
private bool isInitialized = false;
void OnEnable() {
if (!isInitialized) return;
timeSinceLastBlink = 0.0f;
lifeTimer = 0.0f;
}
void Start() {
isInitialized = true;
}
void Update() {
if (!enableBlink) return;
if (timeToLive >= 0) {
lifeTimer += Time.deltaTime;
if (lifeTimer >= timeToLive) {
gameObject.SetActive(false);
timeSinceLastBlink = 0.0f;
lifeTimer = 0.0f;
return;
}
}
timeSinceLastBlink += Time.deltaTime;
if (timeSinceLastBlink >= blinkInterval) {
gameObject.SetActive(!gameObject.activeSelf);
timeSinceLastBlink = 0.0f;
}
}
public void SetBlinkEnabled(bool enabled) {
enableBlink = enabled;
if (enabled) {
timeSinceLastBlink = 0.0f;
lifeTimer = 0.0f;
}
}
}
not to say, using a coroutine or an async method are also totally valid
Ah cool
If I may ask, what's the "if (!isInitialized) return;" pattern for
I've seen it before but it's not entirely clear to me why people use it
deltaTime is fixedDeltaTime in FixedUpdate
and I mean just in general, deltaVel should be proportional to the time step
you could do it in start, but it stops the component from 'reinitalizing' if you enable/disable it, but that also looks like a gpt idea 😄
can't see the Rays cuz they're covered by the mouse cursor
If you Instantiate a Monobehaviour late in a frame, start might not get called until NEXT frame. And some functions need to know if you’ve actually had your Start go off or not yet
OnEnable gets called immediately, right after awake, and that might be your chance to get shit going.
I see, but wouldn't I use "Awake" to initialize most things
Yes, but sometimes you need shit ready before a given event
like let’s say that I instantiate something in a trigger callback
Start will not get called until next frame
now collision callbacks happen, and I find that script, and need to do something on it
problem: it hasn’t had its Start() called yet!
yes, and no, a lot of this depends in how you design your scripts.
https://docs.unity3d.com/Manual/ExecutionOrder.html
this will give you an idea of how, why, and when, life cycle methods are called
Right
also, if you have two scripts on one object that need to initialize, and script A depends on B (so A needs B’s Awake to be done), then that means A needs to be doing something in Start.
But if I make a new object, Awake is called immediately, right?
And in the aforementioned scenario, Start has not been called yet when you need it
Like if I instantiate a new object
So as long as whatever setup the object needs to run is dealt with in "Awake" it's safe to immediately use that object afterwards
and in "Start" I should only put less time-sensitive things like accessing or connecting to other objects
Instantiate(blah);
Debug.Log(“after”);```
If each script on blah has Debug.Log(, then you would see in debug log:
-before
-A Awake
-A OnEnable
-B Awake
-B OnEnable
-“after”
Awake for all that is non-dependent, Start for all that is dependent
the way to think about it is:
-Start has one time in the frame where it gets called
-Start also gets called if you are about to call (or try to call, even if not defined) Update, FixedUpdate, or LateUpdate, if it has not been called yet
that is how I think it works but unity docs aren’t super clear
what you need to know is that you can only depend on Awake and OnEnable to go off on the frame that you come into existence
Start is a kind of shitty initialization method imo. Convenient, but not totally reliable on timing
the secret is to just not use these methods and use assignment methods which then enable update
yeah. I use those when timing matters
I don’t have a general interface for this, because I usually need to call Initialize( as a function with actual arguments
yeah, I have a few places where I explicitly "init" my objects
I don't use Awake or Start for any of my UI components, save for the roots. They get set up by a parent object.
I use Awake a lot
Awake is totally reliable
i usually grab my singletons in awake
or any GetComponent calls
or initialize any arrays etc
OnEnable/Disable are also invaluable when dealing with event registration imo
I'm avoiding Awake in that case because I need to have some data set by whoever instantiates the component
a SettingList needs to be told what setting category it's going to be displaying
yeah, don’t set data in Awake. that will fuck you up
but awake should include any initialization activities that are independent of the contents of any other objects
After Awake, you should be able to call shit without getting NREs and constantly checking for null
also, I wish NRE would tell you which variable was null
any system where velocity changes proportional to your time step will have inertia
example:
velocity += acceleration * deltaTime;
and what about if I am using fixedUpdate
example:
targetVel = controlStickVector * maxSpeed;
velocity = Vector2.MoveTowards(currentVel, targetVel, acceleration * deltaTime);
deltaTime is fixedDeltaTime in fixed update
also i’m talking about your time step, dude. not the specific variable
rb.AddForce(force. ForceMode.Force)
effectively does:
velocity += deltaTime * force / mass;
it calculates the acceleration, using Newton’s second law
Okay, let me try, thanks!
btw
rb.AddForce(force, ForceMode.Impulse);
does:
velocity += force/mass;
which is not proportional to timestep
and just saying:
velocity = maxSpeed * controlStickVector;
is also not proportional to time step
Okay, got it
And what about if I wanted to make that force a problem for the player?
How could I make it so that it is difficult to controll?
the lower the acceleration rate or force, the less responsive it will feel
here, accelRate being small makes it take longer to reach max speed
so if I write rb.AddForce(little force, ForceMode.Force) is less responsive?
the change in vel will be less
A small force will make you more sluggish, yes
Your acceleration will be lower, so it will take longer to change your velocity.
Okay, thanks a lot guys
im having a problem where; once the AI exits the chase state and into the patrol and back into chase, he remains the same 1.5f patrol speed, which is also the same speed as the ai slows down to 8 seconds into chase. i think the problem is to do with the DOTween near the bottom? im not sure tho
also make sure your units are right
a lot of people majorly fuck up units when doing that, which leads to very wrong math
is this correct?
deltaTime has units of time.
position has units of meters
velocity in m/s
mass in kg
force in kg m / s^2…
you cannot add inertia
inertia is a thing you have
and inertia is also not a vector
it is a concept
inertia is tied to mass
acceleration = force / mass
deltaVel = acceleration * time
Bigger mass makes your change in velocity less
a higher "inertia" value would make you accelerate faster here, so that's definitely not right.
do not add a vector to compensate. Just calculate what the movement is supposed to be, and apply
Do you know a video about how can I control my 2D character? I tried 2 hours and I can't manage to moving my character.
yes i know a lot of videos
just use tool called "google"
never heard of her. is she hot?
so I dont get what the solution should be
stop coding and do the math first
you keep jumping into your code without a plan, then waste time because the math was wrong
don't know yet, just discovered it
instead of having a variable for "sluggishness", i would suggest having a variable for force
a sluggish character has a low force
or has a high mass
If everyone has the same force, then heavy characters will feel sluggish and light characters will feel quick
If everyone has the same mass, then high-force characters will feel quick and low-force characters will feel sluggish
Different masses will mean that heavy characters are hard to push around with light characters.
Is it possible to convert PPtr<MonoScript> to fileId and guid from m_Script?
Finally I solved
This is a weirdly phrased question that is surely better suited for #↕️┃editor-extensions . Get the script using a SerializedProperty and then use AssetDatabase functions to get whatever else you want from that
yea I missed the channels sorry
You can also get the script using these functions without even reading m_Script https://docs.unity3d.com/ScriptReference/MonoScript.html
I will write it in #↕️┃editor-extensions
bump
i think you just never kill the coroutines
so SlowDownChump() keeps running after state change
I have a level editor with hotkeys, and I’m contemplating using a command pattern so there is a unique command each frame.
Guys, how to get good at coding movement scripts ??
Any recommendation on how to implement?
consider you also need undo
practice and many projects done with movement
and google
lots of research, look into open source implementations
I have this line of code but I want to switch the mouse press with a key press of E, what would I write?
And any tutorial you have watched that helped you ??
google it
how to detect button press in unity
i keep getting results for some enhanced input system
Okay
then google the old input system
google isnt hard to use
- Separate contact/grounding/specific surface detection into a different class
- Use timestamps to log inputs and when you touch ground. Do not store bools for inputs.
- Use an enum to represent the current state of your player
- Animation and life/death logic needs to go into a different class from movement
because the new input system is named InputSystem
I rlly just needed to change my wording for google damn
google is a skill you need to learn
you are not being helpful.
anyone know how to fix an out of bouds error
