#๐ปโcode-beginner
1 messages ยท Page 127 of 1
Type or namespace name
but I suspect that you're missing a carManager class
No this one is not good
Ok thanks
That's really strange
i don't know how big your grounding check sphere is
yeah well whoever posted the code snippet i copied did not publish their entire project
it's not good if you call Move several times; isGrounded tells you if you were grounded after the last move
You should combine your velocities together and move once
You mean the playerVelocity and the direction ?
Add them all up and call Move() exactly once, yes.
It should be fine if you do the gravity movement last, I guess
but if you do the horizontal movement, then check if you're grounded, you'll get false
because you didn't hit the ground!
Its possible their code snippet was meant to be intended as an example for a particular problem in their project, and not tested copy+paste code
yep thats my guess as well
I can't do that. I Move horizontaly If my character is grounded. I apply gravity if my character is in the air
why not both?
you still experience gravity when on the ground
Yes but if I do that the gravity keep increasing
Set it to zero if you're grounded!
check if the player isGrounded then just set the gravity to 0 every frame
so, every frame, you'll do this
Ok
great minds think alike ig
if (controller.isGrounded)
gravityVelocity = Vector3.zero;
gravityVelocity += Vector3.down * Time.deltaTime * 9.8f;
...
does anyone know why this doesn't work?
public void warningText(string text1)
{
StopCoroutine("warningTextCoroutine");
StopCoroutine("changeText");
StartCoroutine(warningTextCoroutine(text1));
}
IEnumerator warningTextCoroutine(string text)
{
instructionsPanel.SetActive(true);
iText.text = text;
typeWriter.writer = text;
typeWriter.StartTypewriter();
yield return new WaitForSeconds(8);
instructionsPanel.SetActive(false);
}
The controller's job is to figure out how to move without going through walls
It's okay to constantly "push" into the ground
how would i go on about checking if the player has bought a specific item using this approach?
https://hastebin.com/share/ifafocikaj.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
use Debug.Log to check if your code is running at all
also, if this is on a game object that's getting deactivated, that will kill all coroutines on all components on the object
sorry I should have been more specific
The code is running, I Wanted to ask why the StopCoroutine isn't working
my brain forgot to specify lmao
I'm sorry @swift crag but I don't understand. I don't want my character to be able to move while in the air, so how can I merge the two Move ?
ah, you can't mix and match
why not just make hasBought bool public?
If the character is not grounded, don't let the player change their velocity
Oh okay
in every place you call Move right now, replace it with something like
totalVelocity += moreVelocity;
then call controller.Move(totalVelocity); at the end
sorry, I don't fully understand why you mean by mix and match. Should I specify IEnumerator in the StopCoroutine?
If you want to stop a coroutine by name, you must start it by name too
Here's what you can do instead
private Coroutine myCoroutine;
void Foo() {
StopCoroutine(myCoroutine);
myCoroutine = StartCoroutine(Bar());
}
It's fine if myCoroutine is null or a completed coroutine afaik
so this should work, correct?
StopCoroutine(IEnumerator warningTextCoroutine());
because I used IEnumerator
No. That would try to stop a coroutine made out of the return value from warningTextCoroutine()
but that's a completely unrelated enumerator to the one that's already running
Coroutine is returned by StartCoroutine()
You could also do this, though
private IEnumerator theEnumerator;
void Foo() {
StopCoroutine(theEnumerator);
theEnumerator = Bar();
StartCoroutine(theEnumerator);
}
this seems more awkward, though
also, you would not put IEnumerator in there. that's invalid syntax.
warningTextCoroutine() returns an IEnumerator -- an object that gives you values when you ask for them
StartCoroutine takes an IEnumerator and asks it for new values once every frame, by default
So in this code, I save the IEnumerator in a field. That lets me pass it to StopCoroutine() later.
ooooh ok
In this code, I save the Coroutine you get from starting a coroutine
sorry, I started using C# only a few days ago so I'm quite new to this
I presume that, on the inside, Unity keeps track of something like
actually I dunno exactly what it'd be like
it would know which coroutines you started with a string name
and it would know which coroutine each IEnumerator object was used to make
So if you start a coroutine by handing StartCoroutine an IEnumerator, it won't have any clue what you mean when you ask to stop a coroutine by string name
all it knows is that you gave it an enumerator
StopCoroutine(warningTextCoroutine(text1))
This would try to stop a coroutine you never even started.
yes
Ok
Running warningTextCoroutine(text1) executes that method until it hits a yield, then it stops
This was optimisation, not a solution to my problem right ?
No, it's going to make isGrounded more consistent.
yes, I wanted to stop the coroutine before it starts just incase it has been called before
the coroutine starting is based on input
So in general I shouldn't move in two seperate occasions ?
so if the player inputs the same button multiple times I want to stop the coroutine before it starts again to ensure there is no overlap
You will need to store the Coroutine returned from StartCoroutine().
then pass that to StopCoroutine() later
StartCoroutine(Foo());
StartCoroutine(Foo());
StartCoroutine(Foo());
This would start three separate coroutines. Each one is running the Foo method.
StopCoroutine(Foo());
This would do nothing, because each call to Foo() has produced a completely separate object
The fourth one was never passed to StartCoroutine() in the first place!
I think it can be confusing if you're used to passing method names to StartCoroutine
ooooohhh I just assumed Coroutines worked in a similar way to functions but I guess they don't
It isn't gonna do that. It starts a brand new one (unrelated to any already running), and stops that, but lets any other ones keep running
StartCoroutine("Foo");
StartCoroutine("Foo");
StartCoroutine("Foo");
StopCoroutine("Foo");
This would stop one of the three coroutines.
I never use string names, personally
Not sure what you mean. But functions would kinda run the same way (except serially).
so could I just use StopAllCoroutines()?
sure, but why not just store the Coroutine objects?
yeah using the strings requires reflection. passing the returned IEnumerator from a method is cleaner and can support local methods
IEnumerator GimmeNumbers() {
yield return 1;
yield return 2;
yield return 3;
}
GimmeNumbers is a method that gives you three numbers: 1, then 2, then 3
How would I keep my charatcer grounded on slopes. Whenever I sprint down a slope I just fly. I have changed some of the mass variables and other aspects to try and make it stay grounded but nothing has worked
The only thing that's "special" about it is that it can pause itself to yield values.
when you run a coroutine, you give Unity the result of calling a method like GimmeNumbers()
Unity asks the enumerator for a new value once per frame.
each time I call Foo(), I create a new enumerator, totally separate from the rest
they have nothing to do with each other
if I call Foo() a fourth time, I get a fourth, completely new enumerator
You'll want to do something involving the slope's normal
A normal vector is an arrow pointing straight out of a surface
Imagine you're on a 45 degree slope. An arrow pointing straight out will be pointing both up and right.
The green arrow is the normal here.
You'd want to move the player in the blue and red directions.
...rather than in these blue and red directions
hmmm, I have no idea how I'd go around that
I'd have to think on it for a minute!
You could use Quaternion.FromToRotation(Vector3.up, normal) to get a rotation from the second image to the first image
no worries I'll have a look
sorry to bug you again, final question:
if I store the coroutine object does it make another coroutine object every time it runs or is it always store under one object?
where normal comes from a raycast
You'll make a new one every time
Imagine that Coroutine is like a ticket at a deli counter
or a receipt
So the first time you run that method, the field will be null
because you never stored anything in it at all
the second time, it will hold an object that identifies the first coroutine
If the first coroutine is already over, then passing that "ticket" to StopCoroutine does nothing
If it isn't, then unity will stop asking the first coroutine for new values
how would i go on about checking if the player has bought a specific item using this approach?
https://hastebin.com/share/ifafocikaj.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It depends
Where do you want to check it?
In that script itself
would it matter?
Well if you just want to check if it is bought
Just do
bool bought;
Qnd set it to true in the place it gets sold
Where or how are your specific items saved
i want it to be like a certain item. and when that item gets bought, another item recieves a buff. (for example, when A item is bought, the click multiplier of B is multiplied by 2)
When u leave and return to the game?
Are the items always in the scene or do they get spawned in?
Well i mean he has to have an Item list of some sort and if not i recommend adding one
they are in another scene called "Shop". and they are always in that shop scene
I see you have a game manager right? Are you atoring those items there?
You could ads an unityevent to that one item
And u can still use that same script foe the other items
i store them like this, my game manager doesn't handle my items
Ok so
Like the effects of the items each one of them has the script that gives them the effect you want right?
yes, i use a struct to put the effects i want each item to give
https://hastebin.com/share/ifafocikaj.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Ok then it aint that hard just make a variable maybe public or serialized
That holds that script
Yup
Then you assign the object you wanr to it
Make an object of item with name, cost, etc
Then you can make a function that says that when the item u want gets bough
Bought
The other one that was assigned
Gets buffed
And you can make in manny different ways to check if its the item you want maybe use a bool and an if statement
Or use an if statemente and check if the variable of the other script isnt null
It does the thing
Or a unity event
I think the easiest would be a unity event
okay and i do this all in a seperate script right?
Have you ever used unity events?
Nope
no but i could try
oh okay
Ok so go to the script you sent
You assign the Script to your Items in the scene
And write public UnityEvent eventWhenBought;
I feel like I should be able to avoid putting lines 184 and 185 in every single case. But How can I do that with local variables?
After that not sure if the thing u code in will automatically add the using UnityEngine.UnityEvents;
And then put in the script that will get the buffs
put it outside of the switch statement
A public function that applies the buff
but all my items have the same script
And there is not problem
Because the unity event will only do what you assign it to
So tou can only assign the event to the one object
unassigned use of local variable myTween
assign null on the line you declare it on
and don't forget to null check it in your anonymous method
Can you take a screenshot of your buff script rll quick?
oh thanks, I though I tried that, maybe i did var tween = null instead of Tween tween = null
No worries!
i think i got it working
https://hastebin.com/share/ivinebidod.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
YES VERY WELL
yo wait this is so useful
i can literally do this with any item i want
thank you bro ๐ ๐
You could also instead of putting the function to add the buff there you could put it directly in the script u want to buff
And u just drag the other object to there
true
So no need gor as manny varia les
Also is it working already?
Because where you want to make the event be called
So when u buy the item
You have to put
eventWhenBought.Invoke();
No problem! Really glad I helped
it buffs the item after i buy it again right?
or does it just buff it automatically?
Every time u buy it it will get incoked again
So whatever you put in the function you assigned
Will run again
So yes
ah okay
and do i put the evnt on the item being buffed or the item that is going to the buff it?
for some reason it's not working?
Have you invoked the event
Like this
You invoke the event
Where you buy the item
Where tou subtracted the money
yeah
Also have you assigned the event on the inspector?
yes
Ok then it should qork
i feel like im doing something wrong tho
i assign the evnt on the item that is going to buff the other one right?
In this hand of cards, I have it so that when the mouse is hovering over one of the cards, it shifts up slightly and then back down when the user stops hovering over it.
But I also want it to appear in front of the other cards, and then back behind them when the user stops hovering. How can I achieve this?
They're just images on a canvas
if they are transparent then you can use the rendering queue
Image order depends on their order in the hierarchy. You could reparent the currently-hovered card so that it appears after all of the other cards when it's being hovered.
This could be annoying if you're using a layout group though
but Fen's solution is usually what you'd do
Yeah I am ๐ maybe I need to change that though
Haha yeah, I was thinking it was a bit janky ๐
I might honestly just ditch the layout group and manually change their position
you could display another copy of the card on top of the original, maybe
you would make it non-interactable
Oh damn not a bad idea at all.
I need help with my 2d game, I have a system of roads which are each seperate Gameobjects, identical and square, each have 8 points to connect to another road, i need to somehow check if each road is connected by itself, or another road with a certain Gameobject, they should connect via Triggers any ideas how I would do that.
Awesome! I'll give that a shot, thanks everyone!
The sun gets stuck at a rotation of about 90
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateSun : MonoBehaviour
{
// Start is called before the first frame update
public float speed;
void Start()
{
StartCoroutine(updateSun());
}
IEnumerator updateSun()
{
while(true)
{
while(transform.eulerAngles.x < 182)
{
yield return new WaitForSeconds(.1f);
transform.eulerAngles = new Vector3 ( transform.eulerAngles.x + speed, transform.eulerAngles.y, transform.eulerAngles.z );
}
yield return new WaitForSeconds(4);
transform.eulerAngles = new Vector3 ( -1 , transform.eulerAngles.y, transform.eulerAngles.z);
}
}
}
oh it didn't embed
one second
Use a float variable for the sun X angle instead of reading from eulerAngles
Note that the euler angles that you see in the inspector are not always the same as the value that eulerAngles gives you
alr i got it working tysm
I am using rb.Torque() to rotate my snow boarder. My question is I want to check when the Player has made a full rotation, either from rotation right or left. How can I do this?
This is the code I'm using: cs if (Input.GetKey(KeyCode.LeftArrow)) { rb.AddTorque(torgueAmount); } else if (Input.GetKey(KeyCode.RightArrow)) { rb.AddTorque(-torgueAmount); }
Nice ๐
Full rotation since what? Since they left the ground? Like are you trying to detect snowboard tricks, 360 etc?
If that's the case, I would probably check the rotation difference after each physics frame (FixedUpdate).
I would do it with either getting the difference between last and next eulerAngles.y with Mathf.DeltaAngle
Or Vector3.SignedAngle around Vector3.up
Then add that angle difference to some float value
And ofc reset that value when you hit the ground again
i have an issue that I'm not sure how to tackle. I have code that allows the player to rotate a held object by pressing right click and dragging in the desired direction, but when the object has done a full 180 in the left or right directions, the up and down inputs get reversed. How could I fix this?
{
// Rotate the picked up object with the mouse right-click
playerInput.x = (Input.GetAxisRaw("Mouse X") * xTurnRate) * Time.deltaTime;
playerInput.y = (Input.GetAxisRaw("Mouse Y") * yTurnRate) * Time.deltaTime;
playerInput.Normalize();
objectYRot -= playerInput.x;
objectXRot += playerInput.y;
pickedUpObject.rotation = Quaternion.Euler(objectXRot, objectYRot, 0);
}```
Yes, you are correct.
How would I use Vector3.SignedAngle in my case?
Something likecs float angleDiffY = Vector3.SignedAngle(lastFrameForward, transform.forward, Vector3.up);
And ofc you need to store transform.forward in lastFrameForward after the calculations
Does that make sense?
No, I've never used this method.
Did you check the documentation?
Also, instead of Vector3.up you can use transform.up or whatever is your character's updirection, if you want the rotation relative to the player's axis instead of world axis
No, let me check it
It seems like it only checks when the object reaches a 360. Is this true?
No, it gives an angle between -180 and 180
It's the angle between those two vectors, around the axis you specify as the last parameter
ive having a problem where line 174 never finishes yielding. I think its because myTween is not acting like id expect since I declared it like Tween myTween = null; I don't know where to start fixing it though
Okay
You use lastFrameForward, what can I use instead? And what is it?
(!myTween.isActive() || myTween == null)
if its null how could acess it earlier?
#๐ปโcode-beginner message
It's just the transform.forward of the last frame.
@small mantle
You need to store it in a variable in your class
does my switch statement not set it to a tween?
its definitely running the switch statement with the correct case
depends if the incomming case is correct.
I'm printing the result, and if I replace it with Vector3.up or Down it prints 90.
Show your code
float angleDiffY = Vector3.SignedAngle(Vector3.forward, transform.forward, Vector3.up);
Not sure why you put Vector3.forward there
How do I assign a variable to only one clone instead of all of them?
I was checking to see what it would print ๐
Instantiate returns the cloned object. Modify that
var obj = Instantiate(prefab);
obj.myVariable = 123;
i need help i want to check if the current letter from my text is equals to "." but i dont know how to do that
What do you mean store it? What variable would I store it in?
Does the parameter for changeText work here?
[System.Serializable] public struct BeginningInstructionText
{
public string text;
public float time;
}
public BeginningInstructionText[] beginningInstructionText;
public BeginningInstructionText[] fireInstructionText;
IEnumerator changeText(struct arrayName[])
can I use struct like that to define an array?
Have a Vector3 lastFrameForward variable in your class. Then cache/store/assign the current frame's transform.forward in that variable, after you do the angle calculations
So that you "remember" your last forward direction
Did you try it?
So put lastFrameForward in this code: float angleDiffY = Vector3.SignedAngle(lastFrameForward, transform.forward, Vector3.up); ``` Then Right after just make it transform.forward?
Yep
is it possible to register an event to another object's onEnable?
I have this and want to make it "onEnable of target inventory GameObject, run the AddListener and Invoke"
onInventoryChange.AddListener(() => UpdateInventoryUI());
So anytime it "opens", invoke and "Update the Inventory UI". this is assigning/calling it from another class, rather than putting it directly on the object and looking for onEnable
yeah but I didn't know if that was the issue or if it was something else
I don't understand.
but I doubt I can define arrays that way
This part looks wrong: IEnumerator changeText(struct arrayName[])
This? ```
float angleDiffY = Vector3.SignedAngle(lastFrameForward, transform.forward, Vector3.up);
lastFrameForward = transform.forward;```
yeah that was the iffy part
I don't know how I can define arrays like that
Yeah, that gives you the angle difference (delta) from last frame to current frame.
Now you can add that to a float variable that you keep in your class
I am so confused at what is happening. What was the point of angleDiffy?
You don't use struct as a type, use BeginningInstructionText[] instead
yeah I just realized that ๐ญ
are lists of tweens not allowed? its always a null list apparently? I declared it like this
thank you
I just explained that
that gives you the angle difference (delta) from last frame to current frame.
Didn't you want to track your rotation over time?
Yes, but it prints 0? It isn't changing with my rotation.
Initialize the list. Tweens aren't serializable so unity isn't doing it for you
Where did you put this code?
Can you post the full script in a paste site?
In Update
Could someone define Exit Time?
I only have the Rotate code that I showed early, which is in FixedUpdate. I don't think I need to post it.
The minimum amount of time (in % or seconds depending on the settings) the animation plays before it can transition to another one
thanks!
@verbal dome ```cs void Update() {
float angleDiffY = Vector3.SignedAngle(lastFrameForward, transform.forward, Vector3.up);
lastFrameForward = transform.forward;
print(angleDiffY);
}
void FixedUpdate() {
RespondToBoost();
RotatePlayer();
}
Okay, then you will sort it out yourself
Thanks a lot!
This part looks correct to me.
Though I would probably put it in fixedupdate
hi, I have an editor question. Is this the correct channel to ask?
btw, don't scale mouse input by Time.deltaTime. It will introduce frame-rate dependence and lag
I just tried that, it still prints 0
Is this script on the object that rotates?
this shouldn't be an issue if I use fixedUpdate though right?
Yes
No, but it shouldn't logically be scaled by fixedDeltaTime eitherโit just won't cause any issues
what would you suggest instead?
Try moving the code from Update to FixedUpdate, after RotatePlayer
Also print(angleDiffY * 1000) to see if it's just a really small number
Just not scaling by deltaTime at all?
I'm a bit confused by the following:
- if I reference a scriptable object, like
PlayerScoreManagerin a prefab - I'm not able to drag and assign a scene object ofScoreManager - If I do the same to a non-prefab, it works fine
I was really hoping to see the console output of this, but I cannot figure out how to get the debug info/stack. I want to get more info on the Type Mismatch so I can learn.
I'm sure there is a reason for this
It is just 0
mouse input is an absolute value. it is not a rate of change. it should not be scaled by deltaTime.
- playerInput.x = (Input.GetAxisRaw("Mouse X") * xTurnRate) * Time.deltaTime;
+ playerInput.x = Input.GetAxisRaw("Mouse X") * xTurnRate;
- playerInput.y = (Input.GetAxisRaw("Mouse Y") * yTurnRate) * Time.deltaTime;
+ playerInput.y = Input.GetAxisRaw("Mouse Y") * yTurnRate;
It's the opposite, it is a rate of change; it's the amount the mouse moved over the time of that frame
it is already a delta
Then I don't know, I guess transform.forward is not changing.
Or... Your transform.forward is actually up or something?
This is a 2D game btw
Well... That's probably the issue
I mean, it is
You should've mentioned that tbh
honestly this isn't really a concern when it comes to this specific mechanic because its just for rotating a held object, but i do use this method for the player's mouse camera
And, if you just posted the rest of the script like I asked then I would've noticed it @small mantle
of course it's not pre-multiplied or anything, so you could argue it's also absolute. I like to view absolute values as fixed across frames though, like a joystick being held is absolute
I forget this isn't a 2D only coding channel. Sorry for that.
All good. You can probably just change transform.forward to transform.up or transform.right
Okay, let me try
And change Vector3.up to Vector3.forward/back
Because that's the "up" direction in this case, I assume
It's top down perspective, right?
Side Scroller, or Platformer perspective
It's printing huge numbers up to 1000+
Okay so you are only doing backflips/frontflips?
Ok let's forget the SignedAngle.
Use Mathf.DeltaAngle(lastRotation, rb.rotation) to find the angle difference
Store rb.rotation in lastRotation
It's a float
I'm confused on what to convert into what variable from the last example you gave me.
Replace the whole SignedAngle line with that DeltaAngle line
Replace the lastFrameForward variable with a lastRotation variable (and change it to a float)
I hope you understand how it works though. Otherwise I'm just spoonfeeding here
I did what you said, here is what I have ```cs
float angleDiffy = Mathf.DeltaAngle(lastFrameForward, rb.rotation);
lastFrameForward = rb.rotation;
And instead of storing the transform.forward in the variable, use rb.rotation instead
If you did everything I just said then it works
It prints numbers up to 13 and -13. How can I check with a "if" method? Simply, how can I check when I fulfilled the flip.
anyone familiar with unityEvents?
on Events.cs I have this function
public void OnPlaneSpawn(PlaneController plane)
{
m_planes.Add(plane);
}
well this is of course an event. In Spawner.cs I have this
[SerializeField]
private UnityEvent<PlaneController> onPlaneSpawn;
// later on...
// inside a function
ObjectSpawned newPlane = SpawnObject(m_planePrefab); //SpawnObject returns a struct that has the gameObject and a bool telling if it was successfully instantiated or not
if (newPlane.success) {
PlaneController controller = newPlane.obj.GetComponent<PlaneController>();
onPlaneSpawn.Invoke(controller); // here I invoke the function and the error is pointed
m_planeSpawnTimer = 0f;
}
in the inspector I of course set the unityEvent as the image shows
Then when I the game has to invoke the function it gives me the following error
ArgumentException: Object of type 'UnityEngine.Object' cannot be converted to type 'PlaneController'.
bla bla bla...
Spawner.FixedUpdate () (at Assets/Scripts/Gameplay/Spawner.cs:48)
@small mantle When that float goes below -360 or 360, you have performed a back/frontflip. Use an if statement
I'm just confused on how I can check that in a "if" statement. How can I check that its between both -13 and +13?
With the < and > operators. But I don't know why you would want to check that
How do i fix rigidbody movement jitter, its very noticable (for me), in builds. I tried interpolation and movement is called from fixed update. I want to keep rigidbody movement, since its the only way i'll be able to move other rigidbody objects, but this is bad.
I'm trying to check if the player did a 360.
Again, make a new float variable in your class that stores the total angle that you have rotated since you left the ground
Add angleDiffY to that variable every frame
^And then this
if(totalAngle < -360f) Debug.Log("Sick backflip bro");
Damn bro I love you
This? cs float check360 = 0.1f; angleDiffy += check360;
I didn't say "add to angleDiffY"
I said "add angleDiffY to that"
Also the check360 float has to be a class variable (not a local variable in your method). Otherwise it will reset every frame
What should it be at default? totalAngle?
totalAngle is what I'm talking about. You just decided to call it check360
It should be zero by default, of course.
Yes, I changed the name.
When I make a full round, it just keep adding. So its always going to increase?
Yes, or decrease, depending on which way your rotate.
When you hit the ground you want to set it to zero again
OOOOOOOOOOOOOOOOH
(Please tell me it makes sense now)
so If I know this case is running and the tween is being set how could the tween never stop being active? It mentions isActive has weird behavior with recyclable tweens. Im using a local variable which I dont think is the "recyclable" they are talking about. I need to wait till the tween is done then remove it from the list
Yes, much more
Question, would setting the cameras position every frame, to be with the player, be better than it being as a child of the player?
in my opinion yeah. My method of having a player camera is to assign an empty to the player that acts as a marker for where the camera should be when it follows the player. It's kind of the same but fixes some issues relating to movement
One of my main issues is jitter.
are you sure there is actually jitter happening because it could be your computer
I'm getting 90 fps, i doubt its my computer
my home laptop doesn't show jitter but my uni laptop does even though its the same script and setup
if you're confident that it's not a computer issue then it could be an issue of you using fixedupdate for your camera inputs and player movement inputs
generally the advice given to me is to use update for both the camera inputs and player movement because that inconsistency is what causes jitter
What is the -1 supposed to do here, in your own words?
Edit: oh, it's gone
yeah i found the issue
The layermask right? Haha
also from my understanding the -1 is the layer ID for the layermask that it's targeting, and -1 means all layers
why do some of the sentences in my dialogue break like this?
https://hastebin.com/share/xubikaqote.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
its because my camera was intersecting the player's collider, so it couldn't hit the object because it was first hitting the player ๐ญ
Hmm, I think that is not right about it being all layers. But maybe
~1 would be everything except 00..001 (so 11..110)
Note that I said ~ (tilde) not - (minus sign)
if thats what tilde does then what does minus do?
Nothing helpful in this case.
sorry for late reply i went to bed
im using a prefab for the muzzleflash right now
the code im using is here
using System.Collections.Generic;
using UnityEngine;
public class look : MonoBehaviour
{
Transform cam;
Camera mainCam;
void Start()
{
mainCam = (Camera)FindObjectOfType(typeof(Camera));
cam = mainCam.GetComponent<Transform>();
}
void Update()
{
transform.LookAt(cam);
}
}```
i just wanna know how i can make the transform.LookAt method change the rotation the gameobject is facing because the plane that is looking at the camera is pointing sideways to the player so they cant see it
A layermask is a bitmask. It takes every bit and uses it as a flag. If it's a 1, it's on, if a 0, it's off.
Negative one looks to be something like 0010110100110001 in a signed int
No, I think -1 is might actually be correct. Due to how negation works in C# and most other programming languages(2's complement).
Really? Ok. I was trying to look it up but can't find anything useful
i read it in a tutorial so I assumed it to be correct
but i dont think i've seen it referenced in unity documentation
well, i realised i didn't need the layermask parameter anyway and honestly can't remember why i put it there originally
anybody know how i can add a offset rotation to the transform.LookAt method
just add the offset to the (thing ur lookin at's transform)
LookAt(theThing.transform.position + new Vector3(0,0,0))
Use the quaternion look rotation method then add your own offset after with the result. Or use an offset to the position before passing it into the method. Depends what offset you need
or afterwards, yea.
Just tried it out.
int i = -1;
Console.WriteLine ($"binary: {Convert.ToString(i, 2)}");
It prints 111111...
Ok nice. Good to know. Really appreciate you taking the time
How do I respawn pieces in a falling block game after they hit the ground?
how do i apply it because im new to c#
transform.LookAt(cam * Quaternion.LookRotation(90, 0, 0));
@tender breachMove them or Destroy and Instantiate new ones?
Use OnCollisionEnter or OnTriggerEnter and see if the collision is from a block. If it is, destroy it (or as Zyme said, move it)
so i'm working on a 2d platformer with a speed boost mechanic. it's specific to the player and affects the ui's color and player sprite color. right now pretty much anything player related is in a single PlayerController script. would it generally be better practice to split it into separate scripts like PlayerController (for basic movement), BoostLogic, and another script for the ui and sprite color change? none of these are used by anything else
@arctic harborUse events
So you need a rotational offset?
Yes
The parameter in LookAt needs to be a Vector3, so that won't work like this.
You could do something like transform.rotation = Quaternion.LookRotation(cam.transform.position - transform.position) * Quaternion.Euler(90, 0, 0)
Multiplying by that Quaternion.Euler is what "adds" to the rotation
Or if it's simpler for you, first do LookAt normally, then transform.Rotate after that
not really sure what you want the offset to be exactly so i cant suggest much
what osmal said is what I initially was thinking for a rotation offset, if you want it to be a position offset then #๐ปโcode-beginner message this should be fine
Question, if i set the players cameras position to the body, should i use update or something different?
Usually LateUpdate
Okay thanks
Why does unity error when It cant find a key in a dictionary?
Now i have one issue, the player is moving, but it doesnt take in account of the cameras rotation, how do i fix this?
just looked it up and i don't see how to use it as a sort of toggle. i want the ui and player to glow when boosting, and normal when not. boosting itself is only available under certain conditions as well
That's a C# thing, not a Unity thing.
You can use TryGetValue to be safe
I'm trying to check if a key exists but if it's been removed it obviously wont find it so it causes an error so I cant even skip it before error
if an object has 2 colliders, and another object collided, how do i know which of the 2 colliders were hit? the oncollisionenter function is in the object with the 2 colliders
You can if you use TryGetValue
That's kinda what it was made for
@arctic harborWhen you activate boost you send out an event, and other script like GUI and whatever can listen to this action and act upon it.
Separation of concerns, so you put an event listener in your GUI handler
Why cant i move my player when the player is looking completely down? ``` targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity.Normalize();
Vector3 cameraForward = Vector3.Scale(playerCamera.transform.forward, new Vector3(1, 0, 1)).normalized;
Vector3 moveDirection = cameraForward * targetVelocity.z + playerCamera.transform.right * targetVelocity.x;
Vector3 moveVector = moveDirection * playerSpeed;
rb.velocity = new Vector3(moveVector.x, rb.velocity.y, moveVector.z);```
Because cameraForward is completely zero when you look down
Oh, how can i fix this then?
For example, get a rotation that only uses the camera's Y angle
Then rotate moveDirection with that quaternion
Quaternion.Euler(0, playerCamera.transform.eulerangles.y, 0)
Well my issue is not rotating the player, its about moving in the same direction of the camera.
Ok well I didn't talk about rotating the player at all
I'll try this
If you do that then get rid of cameraForward
so transform.rotation = Quaternion.Euler(0, playerCamera.transform.eulerangles.y, 0)
?
Nah, make a new Quaternion out of that
Then multiply moveDirection with that quaternion to rotate moveDirection
Hmm wait
What will that quaternion go into then?
You should change the moveDirection line to cs Vector3 moveDirection = thatRotation * new Vector3(targetVelocity.x, 0f, targetVelocity.z)
So you have a velocity on the XZ axes that you rotate with the camera's Y angle
The end result should have a Y value of 0
Here it is now ``` targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity.Normalize();
Vector3 moveDirection = Quaternion.Euler(0, playerCamera.transform.eulerAngles.y, 0) * new Vector3(targetVelocity.x, 0f, targetVelocity.z);
Vector3 moveVector = moveDirection * playerSpeed;
rb.velocity = new Vector3(moveVector.x, rb.velocity.y, moveVector.z);```
it works but my movement is delayed.
I don't think anything here would cause a delay
I still get the same error even with TryGetValue ๐ค
Show the error and your code
I'm not sure at this point
That doesn't address how boosting is a toggle. I can send out an event to change the UI color upon starting a boost, sure, but then I'd have to send out another event when boosting stops. Boosting can be stopped simply by releasing the boost button or by expending the boost resource. It seems more intuitive to just have a isBoosting boolean and have things look at that
Oh god is this that voxel thing you showed yesterday
yeah it's really frustrating that I cant just check if the xyz index exists that would solve all my problems
As suggested, you could just use a single Dictionary with Vector3Int as the key
hey i need a little help, i made a procedural room generation script, but this weird bug happens, it seems like sometimes the rooms generate in a circle and block the player off from progressing throughout, as shown in the video, it only happens sometimes
I want the Player to have their Camera Change, but I also want the Player to be pushed. How can I do that without making more bools? I just don't want to make more bools because code will start getting messy. cs void Update() { if (playerFlipped) { followCam.m_Lens.OrthographicSize = followCam.m_Lens.OrthographicSize + 1f; rb.AddForce(Vector2.right * flippedBoostPower, ForceMode2D.Impulse); playerFlipped = false; } }
If you keep these implementation, you'd need to call TryGetValue on every single dictionary in that chain.
does anyone know how to solve this?
@arctic harborDepends how large your project is and how you want the structure to be. Everything can be solved in multiple ways. If you have a lot of things "looking at" stuff you are creating dependencies that can break if you change something. If you use events it is easier to decouple the scripts. The new input system for example works this way. You send event when you press down a button, and event when you stop pressing and act upon it. And how are your other scripts going to look at the boolean continuously?
does someone know whats the point of skinWidth in creating a player controller using translate?
It helps to avoid getting stuck or shaking, as far as I know
Hmm. It's just a simple platformer
don't use playercontroller with translate..
Impossible to say anything without knowing how your procedural generation is working and debugging through it.
I meant making a player controller using translate
Right now I have a BoostLogic method that runs in FixedUpdate of PlayerController and an isBoosting check inside of it. I added the UI color change to the isBoosting check afterward
why ? do you not want collisions
I do but I have seen people say it allows more control and I can use ray cast to do collisions
probably not worth doing it with translation
I wanna at least try. If it gets to tedious il go back to physics
What skinWidth? Where do you see it?
And what makes you think that there's any point at all?
in a video about how to make a playercontroller they use skinWidth to shrink the bounds of the collider and raycast from those bounds to stop the player from getting stuck. I thought about doing it because I was struggling getting the movement I wanted with physics and Thought I would get better results with translate.
there are better ways to fix getting "stuck"
I'm only using it because the tutorial is
๐คทโโ๏ธ sounds like a poor tutorial
It does sound like a pretty bad walk-around ignoring the real issue.
That being said, we know literally nothing about the issue that you're mentioning, so can't really say anything about it.
Nor did you explain what object does the skinWidth property belong to.
Or any other info about your setup.
So would it be better to just use physics?
depends, what is the original problem? when is it getting "stuck"
usually that can be fixed with step height/ skin or also the Physics settings
The problem wasnt getting stuck. I was just confused about what skinWidth was and its purpose when I was following the tutorial.
What class/type does this property belong to? Can you answer that one question?
What skinWidth are you talking about?
How would you make the event system work if the boost resource is tied to the player? I'd assume you would still need a GetComponent<PlayerController> in the event manager script. And then send an event upon starting a boost and send another event upon ending a boost?
Two colliders can penetrate each other as deep as their Skin Width. Larger Skin Widths reduce jitter. Low Skin Width can cause the character to get stuck. A good setting is to make this value 10% of the Radius.
also like other people have said, stop using translate if you want any form of collision
you're looking for CharacterController.Move()
whats wrong with just raycasting
for movement?
for collisions
because it's silly
the character controller, and most other 3D character controllers use depenetration
they move into an object, then figure out how much to move until they're just out of the object. to simulate a hard collision
then the render occurs. etc
What if you spawn already colliding? Or move so fast that the raycast wouldn't hit anything?
ok I get it. But do you think unity's physics can make movement on par to platformers like hollow knight or celeste?
I mean, you could compensate with raycasting ahead the amount you would move and do overlaps too. But that would basically be a shitty copy cat of the physics system.
unity's physics engine is just physx.
which is used by most of the gaming industry
The movement part is up to you.๐
ok Thank you
*if you're in 3D
yes
those controllers use also raycasting , like down for things like coyote time and whatnot
ok ty
@arctic harborWhat is a boost resource? A pickup? When you use the BoostAction function you send OnPlayerBoostEvent?.Invoke(this) and then in any script that cares about this action, like GUIHandler you subscribe to it in OnEnable and OnDisable. You don't need to reference PlayerController because the messaging is done via events
And then OnPlayerBoostEndEvent?.Invokte(this)
Something like this:
public class GUIHandler : MonoBehaviour
{
// Subscribe to events
private void OnEnable()
{
OnPlayerBoostStartEvent += OnPlayerBoostStart;
OnPlayerBoostEndEvent += OnPlayerBoostEnd;
}
// Unsubscribe to avoid memory leaks
private void OnDisable()
{
OnPlayerBoostStartEvent -= OnPlayerBoostStart;
OnPlayerBoostEndEvent -= OnPlayerBoostEnd;
}
private void OnPlayerBoostStart()
{
Debug.Log("Player started boosting.");
// Color the GUI or something
}
private void OnPlayerBoostEnd()
{
Debug.Log("Player stopped boosting.");
// Fix GUI color
}
}
How come c# wont allow you to modify a dictionary while iterating over it?
Race conditions?
no
@meager gustElaborate
Race conditions generally involve threads. Updating a dictionary value invalidates the iterator
So is the problem that you have unreachable rooms?
You would need some kind of graph structure to make sure it's all connected
The player has a resource bar for boost. There are no pickups. The player gains boost resource by moving
How am I supposed to make changes to a dictionary then?
So, if I want an animation to start a specific frame, how do I do that?
show your code, what changes are you trying to make?
put your objects in a list
iterate the list, and mess with the dictionary while you're doing it
u can just loop thru the kvp
it wouldn't let him
you need a list like you said, iterate thru keys
I'm trying to change and remove some values of my voxel data
yea makes sense, you're trying to add values to the keys while iterating through it
Only reason it doesn't work but I'm trying to understand how I can possibly get around this
maybe different type of loop
just told you. make a struct with your key etc info, put it in a list, iterate through the list while accessing the keys in the dictionary
How could i do that?
Yeah
How do I make instantiate only spawn one sprite via OnTriggerEnter2D? https://pastecode.io/s/0q8w5e2f
whats wrong with it now?
also mixing physics and translate = bad
I want the gameObject to spawn once via OnTriggerEnter2D, but it spawns mulitple times.
are objects passing the trigger multiple times ?
No, only once
do u see an issue with this?
Didn't you read the code?
No
i really wasnt expecting that as an answer
You set it to true and immediate check if it is true.
You see no issue with that?
Honestly, no.
How?
then maybe take a break from unity and do some basic c#
you don't know what your own code does?
why did you put that there then
If you set it to true. Then it will not be false. So why even set it or check?
The if will ALWAYS be true
So what should I change the code to?
if(!spawn){
spawn = true;
//etc..```
Not to set it to true before checking if it's true
I have two singletons, the second relies on the first to have registered some values in a struct and both run Awake() and the second singleton gets no reference error in OnEnable(). Can I delay the second singletons awake, or set an execution order or something. Or a better pattern
what, i literally (wrote it)[#๐ปโcode-beginner message]
Let's start simple. What's the intention begins these 2 lines in your code?
Spawn = true;
if (Spawn == true)
I'm trying to spawn a gameObject only once when Spawn = true.
also don't forget code runs from top to bottom
Okay, and when is it supposed to be true?
When it touches OnTriggerEnter2D
but if you keep setting it to true it will keep doing it lol
defeats the whole purpose of a bool
lol, the code have too many if condition
It does that already even if you remove these 2 lines.
What would you guy's say is the best method of crouching for 3d First person games?
best method in what sense?
shrink the collider/move the center. done
move the world upwards
I don't believe in best for most things. But what nav said is very common
Yea i'm doing that, but i want to move the camera down.
My setup is very janky
move the cinemachine target to the head bone or something
Fix the setup then
{
GetComponent<CapsuleCollider>().height = Mathf.MoveTowards(GetComponent<CapsuleCollider>().height, CrouchHeight, Time.deltaTime * CrouchingSpeed);
GetComponent<CapsuleCollider>().center = Vector3.MoveTowards(GetComponent<CapsuleCollider>().center, new Vector3(originalScale.x, CrouchCenter, originalScale.z), Time.deltaTime * CrouchingSpeed);
Joint.transform.position = Vector3.MoveTowards(Joint.transform.position, new Vector3(Joint.transform.position.x, -1.71f, Joint.transform.position.y), Time.deltaTime * CrouchingSpeed * 10);
}
if(GetComponent<CapsuleCollider>().height == CrouchHeight && Joint.transform.position.y == -1.71f)
{
Crouching = false;
isCrouched = true;
}
if (GetComponent<CapsuleCollider>().height == OriginalHeight && Joint.transform.position.y == OriginalCameraHeight)
{
Standing = false;
isCrouched = false;
}
if (Standing)
{
GetComponent<CapsuleCollider>().height = Mathf.MoveTowards(GetComponent<CapsuleCollider>().height, OriginalHeight, Time.deltaTime * CrouchingSpeed);
GetComponent<CapsuleCollider>().center = Vector3.MoveTowards(GetComponent<CapsuleCollider>().center, new Vector3(originalScale.x, originalScale.y, originalScale.z), Time.deltaTime * CrouchingSpeed);
Joint.transform.position = Vector3.MoveTowards(Joint.transform.position, new Vector3(Joint.transform.position.x, OriginalCameraHeight, Joint.transform.position.y), Time.deltaTime * CrouchingSpeed);
}```
Cinemachine
Cinemachine
Edit: oh double ๐ฆฅ
private void CrouchCheck()
{
// a little jerky
if(Input.GetKey(KeyCode.LeftControl))
{
isCrouching = true;
// Height and Center deltaMaxs need to match
characterController.height = Mathf.MoveTowards(characterController.height,1f,(7f * Time.deltaTime));
characterController.center = Vector3.MoveTowards(characterController.center,playerSettings.crouchingVector,(7f * Time.deltaTime));
}
else if(!obstacleOverhead)
{
isCrouching = false;
// Height and Center deltaMaxs need to match
characterController.height = Mathf.MoveTowards(characterController.height,2f,(5f * Time.deltaTime));
characterController.center = Vector3.MoveTowards(characterController.center,playerSettings.standingVector,(5f * Time.deltaTime));
}
}```
I'm doing it here, but it goes very slow, and doesnt stop at 1.77
else move ur height, and ur center the camera (if parented) should follow along
but cinemachine fr
I had the camera as a child before, but had to remove it because of jitter, so now i have to move it manually.
prob wrong lerp
does it pretty smoothly
Here it is: ``` if (Crouching)
{
GetComponent<CapsuleCollider>().height = Mathf.MoveTowards(GetComponent<CapsuleCollider>().height, CrouchHeight, Time.deltaTime * CrouchingSpeed);
GetComponent<CapsuleCollider>().center = Vector3.MoveTowards(GetComponent<CapsuleCollider>().center, new Vector3(originalScale.x, CrouchCenter, originalScale.z), Time.deltaTime * CrouchingSpeed);
Joint.transform.position = Vector3.MoveTowards(Joint.transform.position, new Vector3(Joint.transform.position.x, -1.71f, Joint.transform.position.y), Time.deltaTime * CrouchingSpeed * 10);
}
if(GetComponent<CapsuleCollider>().height == CrouchHeight && Joint.transform.position.y == -1.71f)
{
Crouching = false;
isCrouched = true;
}
if (GetComponent<CapsuleCollider>().height == OriginalHeight && Joint.transform.position.y == OriginalCameraHeight)
{
Standing = false;
isCrouched = false;
}
if (Standing)
{
GetComponent<CapsuleCollider>().height = Mathf.MoveTowards(GetComponent<CapsuleCollider>().height, OriginalHeight, Time.deltaTime * CrouchingSpeed);
GetComponent<CapsuleCollider>().center = Vector3.MoveTowards(GetComponent<CapsuleCollider>().center, new Vector3(originalScale.x, originalScale.y, originalScale.z), Time.deltaTime * CrouchingSpeed);
Joint.transform.position = Vector3.MoveTowards(Joint.transform.position, new Vector3(Joint.transform.position.x, OriginalCameraHeight, Joint.transform.position.y), Time.deltaTime * CrouchingSpeed);
}```
but theres still a bit of jerk.. but its very subtle
interesting.. why this way instead of coroutine vector3.lerp?
fair enuf haha
MoveTowards works a bit differently.
i used it so i wouldnt have to create a 2nd variable for two parameters
just to do the lerp the correct way
so messy , these should be diff methods. and cache those components
but ya, if i were to do it again id just do some proper lerps
this dude does it pretty well coroutine here
https://youtu.be/-XNm7dPVVOQ?t=738
Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!
Join me and learn your way through the Unity Game Engin...
Would translate be bad to use.
If you have a rigidbody, then definitely. If not, then probably
how would i add choices to this dialogue system?
https://hastebin.com/share/cofeqawero.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
probably SO or something
I would personally use Ink instead of building my own
you'd have to make a couple more lists, one of responses, and another for the response to ur response..
whats lnk?
oh alr
then when click it responds.. waits for u to respond back.. and then responds according to how u responded..
it'd be much bigger and more complicated than what u have now
Its a really good asset for this stuf plus choices
ink, not Lnk
ah yes ink not lnk
In this video, I show how to make a dialogue system with choices for a 2D game in Unity.
The dialogue system features Ink, which is an open source narrative scripting language for creating video game dialogue that integrates nicely with Unity.
Thank you for watching and I hope the video was helpful! ๐
NOTE ABOUT INPUT HANDLING - If you're try...
heres a video that implements Ink
this guys video helped me greatly
also this guy https://www.youtube.com/watch?v=-nK-tQ_vc0Y
Ever wonder how to convey your characters' thoughts or have your game talk to your player? In this tutorial, we take a look into a script tool called Inky from Inklestudios and write up a small dialogue for Phoenix wright in Unity!
Resources
Ink by Inklestudios: https://www.inklestudios.com/ink/
Brackey's Dialogue System: https://www.yout...
mobile dev, here i come ๐
was waiting til i got a phone with a gyro
christmas provided
android is dumb easy, IOS not soo much esp if you're on an old mac with old xcode
ah, thankfully im windows, xbox, and android
I'd love to get myself some VR for development ๐ฎ
AR seems like it could be cool
still pretty early.. time to get ur foot in the door with something
yeah esp the face topology stuff / filters
How do i make .movetowards not infinitely move, and stop at the target point.
you should just do it this way
#๐ปโcode-beginner message
while loops, coroutines, wrapping it in a basic conditional..
// do math to find out if your near target
if(not near target) --> keep movetowards-ing
else (if near target) --> don't
How do i scale a object from its pivot from a script?
uh, if you consider setting it via script is automatic
unless you mean by transform handling matrix transformation then sure
so i have my player not destroy on load and when they enter a specefic scene i want to reset their location
how can i do that
Have a script on an object in the new scene and have the position as a variable. Have it set the players position to it via player.transform.position = resetPosition
I give this method for its sheer simplicity. There are many other ways
how do i reference the player to it
Well, you could have the player register itself to a singleton, and get it from that singleton (i recommend that over making the player itself a singleton), or use findobjectoftype.
Or anything from here
https://unity.huh.how/programming/references
does anyone here know anything about git for collaboration in unity?
I'm sure most everyone here does
It's the industry standard
cool, I have a super specific question
Lots of people know lots of things. If you have a question, ask it
This code makes the muzzle flash look at your main camera
if I want to merge two branches on git, is it possible to combine the additions on both branches when merging?
For example:
that's what merging does
i fixed my issue already it was this
transform.LookAt(cam);
transform.rotation *= Quaternion.Euler(90, 0, 0);
???? I looked it up but it said that it just overwrites what is on the branch
Not sure where you read that
This will rotate it 90 degrees in the x axis, yes
it's called "merge" for a reason
yes, the muzzle flash was pointing itsself at the camera at the wrong angle that was my issue
But I'm guessing you are making an instance of the muzzle flash prefab?
yes
it works fine now so ye
okay so, let me put this into practical terms so I can better understand. If I have a base game on git and a friend and I are developing it at the same time. One of us uploads to branch 1 and another uploads to branch 2. If we were to merge these branches it would combine the files that both people added, right?
hey so none of my code deals with gravity i use a rb2d for that but for some reason i still fall even if i set it to kinematic
You always merge one branch into another. The branch that is merged INTO, will contain the changes from both branches after merging.
e.g. if you do
git checkout a; // check out branch a
git merge b; // merge b into a
branch a now has the changes from both branches. At least on your local machine.
it seems i had so much built up velocity it didnt matter lol
You can just set the rotation of the instance directly when you Instanciate it
but then it wont follow my camera when i move too fast
I know this is restating the exact same thing but I want to be 110% clear before I mess up any files
so if branch one has A,B, C, and D
and branch two has A,B,C, and E
if I merged branch 2 into branch 1, branch one would have A,B,C,D, and E?
it's very hard to mess things up with git. Just make sure you've committed and it won't be a problem
when you merge it will create a merge commit
if you don't like the results you can just roll back that merge commit
Are these commits? Yes.
Do note that whenever you merge there's the chance for conflicts
public Transform FirePoint;
//some shi here
Instantiate(Prefab, FirePoint.position, FirePoint.rotation);
@radiant sail
alright one more question and I will get out of your hair.
What if branch one has A,B, C, and D
and branch two has A,B, and E without C
if I merged branch 2 into branch 1, branch one would have A,B,C,D, and E or A,B,D, and E?
what does E without C mean
sorry, should have been more specific.
branch twos previous commit had A,B, and C. This commit got rid of C, but branch one still has it
It doesn't have to, but I'm pretty sure you can make the instance follow the fire point as well
I'm not 100% sure I follow here. Are you talking about a revert commit?
Something like Vector3.MoveTowards or Vector3.Lerp to make it move smoothly towards the FirePoint transform @radiant sail
not really, one second I will try to explain better
ok
Branch 2 and Branch 1 both have file A,B and C.
One commit, Branch 2 gets rid of file C but Branch 1 still has it.
If we merge branch 2 into branch 1, what happens to file C?
Wait now we're talking about files? I thought we were talking about commits
???? we were always talking about files
It depends. Did branch 1 add the file? Or it just didn't remove it?
I was talking about commits
just didn't remove it
Also, if you leave too many instances, memory might accumulate over time if you keep the unused Prefab instances. A quick solution might be a coroutine to delete all unused instances. But if you want to latch onto this system consider maybe making an object pool. I still recommend maybe just enabling/disabling the muzzle flash Prefab instead of cloning a new one every time you shoot
Then it will be removed. Because the commit from branch 2 will be applied and remove the file
You need to think in terms of commits, not files.
i already delt witrh that, i made a script where i can set a certain time and the intance deletes itself
so i decided to use findobjectoftype and my player is a clone of a prefab so would i include the (clone)??
Alright, that should work as well
I'm trying to hold a gameobject on mouse cursor, but it keeps flickering and bouncing as if the transform pos gets reset every frame or something
well the Update version of this will be much more consistent
If that matters in your game.
isnt waitforsecond timing things well?
like 100x of waitfor5sec is almost very very very close to 500 seconds perfect?
WaitForSeconds(animationDelay) will wait until the next frame after that amount of time passes. So for example if animationDelay is 5, then it might wait 5.02 seconds if that's when the next frame after 5s runs. That means your timer is off by 2 hundredths of a second. This error will compound over time
in contrast the other thing you have is properly accounting for these interframe timing errors in the timer variable
note that you can achieve that same thing in a coroutine too
you just have to use the same timer technique and yield return null
or.. maybe i can add an extra float that captures the deltaTime and reduce than on the next WaitFor
but would be like quite uglier than the update, yea
Not sure how that would actually work, and sounds more complicated
WaitForSeconds(animdelay - lastdeltaTime)
let's say the frame timings are:
4.98, 5.03
Time.deltaTime would be 0.05. Where do we get the 0.03 we actually need from?
I don't think you can do it without your own timer, which is exactly what the other method is.
maybe if you made a CustomYieldInstruction version of WaitForSeconds that has a .TimingError property
right yea
that would, of course, be holding its own timer inside itself
so again it's kinda the same timer solution just with a fancy wrapper
whats the best way to add every gameobject that has the layer Player to a list
for what purpose
so i can reset there posistion
that's not very descriptive at all
so bascially i have multiple players from another scene when they get in the new scene i want to reset there position
so they dont get to the new scene and fall
if "every gameobject that has the layer Player" is just the player objects, then have them register themselves with some spawner or manager or whatever when they spawn
this isn't really what layers are for
just add them to the list as you spawn them
they are spawned in another scene\
the list is on a object in the new scene
or have them subscribe to the onSceneLoad sceneLoaded event and reset their positions themselves
keep the list in the first scene and/or in a DDOL object
pass the list to the second object as needed
ok thanks
Vector3 mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
mousePos.y = 0;
_currentObjectOnCursor.transform.position = mousePos;
Why does this not instantiate object at correct pos? The object is way off the mouse cursor
Ortho camera if it matters
off how? also keep in mind that it will set the Z position to that of the camera's position so the object will be too close to the camera to be visible
Half the screen down from cursor
so the issue is the Y position then. which you are conveniently setting to 0
are you sure you don't mean to be setting the Z axis to 0 there?
But the Y is up?
yes, and if the object is ending up below the cursor's position then its Y position is lower than the mouse cursor's y position
because you are setting its Y position to 0
I need it to spawn on 0 on the Y axis
is the camera orthogonal or perspective?
Ortho
okay so why are you surprised that the object ends up at Y 0?
oh you have said that, i overlook it, btw 2d game is x-y plane by default
take this poor drawing for example. let's say that black line near the bottom represents Y: 0. the red spot on the cursor is the cursor's position, the blue spot is where your object will end up because you are setting it's Y position to 0
FindObjectOfType takes a type, not the name of the gameobject.
For example, say you have an object called "Player (Clone)", and it has the script PlayerData on it, you could do FindObjectOfType(PlayerData) but you could not do FindObjectOfType("Player (Clone)")
You COULD do Find("Player (Clone)") but I strongly recommend against the base Find method. There is also FindObjectWithTag (if I remember the name correctly).
However, saying all that, you generally want to avoid any of the find methods. They are quite inefficient. The base Find() method is also very brittle
the red dot is your cursor, yes?
Yep
and 0 on the Y axis is where that block is located, yes?
I assume so
so then what is the issue? it's going exactly where you are telling it to. your mouse cursor's X and Z position and 0 on the Y axis
so you need to set the Z coordinate
too close to the camera as i already pointed out
I guess I need a two step solution. Because I only want it to move after the cursor on X and Z axis
you want it to be a bit ahead of the cursor's z axis, or just at 0 on the Z with your camera at -10 since that is typically how you would do it with 2d
what is the best way to collaborate on a unity project at the same time?
git
git
wouldn't that cause alot of conflicts?
how so?
Only if you fail to use git correctly
I just tried it out, different additions to scenes will cause conflicts
yes, do not work on the same files at the same time
when merging*
this is typical with any version control
Thats where conflict resolution comes in
yeah but there is no option to just combine data, instead you must pick between one set of data and another
yeah, that's why I was wondering if there is a way to collaborate at the same time
if you mean working on the same files at the same time in real time, then no. learn how to properly use version control
There is a option to combine data but if two people changed the exact same thing then there is no way to combine. Lets say I move a cube to -5 on the X and you move it to +15 on the X. What should happen now? The cube goes to +10 ? Thats not correct at all since now both our work is lost. Hence a choice has to be made
So if I created a cube on a scene in one branch and create a sphere in another branch and try to merge them it won't cause problems, right?
Smart merge also improves merging for Unity asset files https://unity.huh.how/info/git#configure-smart-merge
Yep I was just about to mention the YAMLMerge
what does it mean by "can merge scene and prefab files in a semantically correct way"? Is that being able to fully merge scenes without conflicts?
It means it has some awareness of how yaml is structured so it doesn't just treat it entirely as text
without it git's default merge can mangle the yaml
How to check if Vector3 is 0,0,0?
just compare it to Vector3.zero
a == b
Try asking in the non coding channel #๐ปโunity-talk
Delete the message here and repost it over there.
why does the raycast not hit the collider? the collider is on a cube with a transparent material
void GroundCheck()
{
float distance = 1f;
Vector3 dir = Vector3.down; Vector3 raycastOrigin = transform.position;
Debug.DrawRay(raycastOrigin, dir * distance, Color.red);
if (Physics.Raycast(raycastOrigin, dir, out hit, distance))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
}
this code works here (mesh collider)
Debug.Log($"hit: {hit.collider.name}");
i'm getting a null reference on the first one
wdym on the first one? and did you put this inside the Physics if statement
i put it after
on the transparent cube, no colliders are hit
then its probably not long enough ray
should be at the feet anyway, why is it in his mid
i just drew the ray at the position.
the ray works for the ground, i thought it would work for the cube since he can run on it too
If this is a default capsule or character controller, 1 unit down from its center will not be long enough
The default capsule is 2m tall
the scale is 1, i change the ray distance to 1.5 and it worked
i don't know why it works on the ground but not on the cube he's literally running on
Right scale 1 on a 2m tall object means it's 2m tall. 1m is not enough to reach the ground from the center
thanks for the help
how would i make a player appear at the location of a game object?
like how would i teleport a player to a gameobjects location
Just set its position to that object's position.
Of course this could be complicated by whatever movement mechanism you're using
so like make the players transform = the targets transform?
right
and if i have a serialized field for the transform of the object can i just put that variable.position?
is this the best way to do screen transitions?
i made a screenbox, and i wanna go to another screenbox when i hit the edge of the first one
so i check if the player is there then i activate the next one and deactivate the current one
teleporting the player into the next one
thats how i did it
Is it the... Best way? I don't really know how to answer that
What do you mean by "best"?
nvm
Any good toturial to start programming in unity
check pins
there are beginner c# courses pinned in this channel. and the pathways on the unity !learn site are a great place to get started with learning unity after you know the basics of c#
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is there another thing i need to learn before starting becuase i already learned c#
did you just stop reading at the first .?
you already know all of c# ?
Most of it
then you should be familiar with reading an API
https://docs.unity3d.com
unity is just an api
c# in unity different from c# outside a little bit btw
and I doubt you know most of c#
no it is not
also the async await part
works fine for me, what do you mean it has issues?
weird I gotta try again, idk last time it just never returned from the delay for me
it just kept "waiting" in limbo, i prob did something wrong tho ๐
i will also note that i'm using 2023 with the Awaitable class
Ohh
though i can test it again with a method that returns Task instead
last time i did it was 2021 prob why. I will try my 2022
yep works just fine for me. are you sure you weren't perhaps trying to use part of the Unity API off the main thread and that thread just shut down instead?
Task.Yield reduced my framerate.

Then I started using UniTask.
Works a lot better.
yeah possible, I did it a year or so ago
well it worked this time ๐คทโโ๏ธ
async void Awake()
{
await Task.Run(() => Debug.Log("Print before Delay"));
await Task.Delay(400);
await Task.Run(() => Debug.Log("Print After Delay"));
}```
not sure what I did wrong last time
probably just accessing unity stuff off the main thread. especially if you were using Task.Run, that schedules tasks to run on the thread pool
its strange because I only put Task.Run this time, but just tried it without it and still works, who knows what I did last time
just glad it works here too now ๐
oh, the language itsslf is the same but the way of development should be different from other c# application?
though it is same for developing in different frameworks
depends which framework you pick
most of the .net core are the same though
I love MAUI and Blazor
the dependency injection system there is grand
but its same as WEB API
How can I save/load data in WebGL without using playerprefs?
Json, File.WriteAll solution doesnt work(the file is not saved in the webgl).
Webgl has browser storage
lemme find the link
Console app, winform app, mvc app, uwp app, unity app, all require different approachs if that is what you mean, but all can use identical C# and .Net
What do I do to use browser storage?
docs say to use Application.persistentDataPath, I guess that I cant use File.Write in webgl?
PlayerPrefs it will store it here
https://developers.google.com/web/ilt/pwa/lab-indexeddb#overview
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
On that note, if I need different save system for webgl, is there a way to detect if we are on webgl build so I can call correct save/load script?
So playerprefs is the way to go?
yes, you use PersistentDataPath and you can use System.IO
its one way to do it sure
you can also just use local files anyway
System.IO doesnt seem to work with webgl for me
Or maybe its json that doesnt work
works for me
what doesnt work exactly do you get error?
private void SaveGame()
{
GameSave save = new();
save.Gold = Gold;
string saveData = JsonUtility.ToJson(save);
string filePath = Application.persistentDataPath + "/Gold.json";
System.IO.File.WriteAllText(filePath, saveData);
}
private void LoadGame()
{
string filePath = Application.persistentDataPath + "/Gold.json";
if (System.IO.File.Exists(filePath))
{
string saveData = System.IO.File.ReadAllText(filePath);
Gold = JsonUtility.FromJson<GameSave>(saveData).Gold;
}
}
}
[Serializable]
public class GameSave
{
public float Gold;
}
No error
just doesnt load the data
but it saves(the "filePath" shows if I do Debug.Log(filePath); in webgl
But the indexdb is empty(for that specific path)
this will not save to indexeddb
yes it will
it goes in your User/AppData/LocalRow
not in WebGL
I need it for webgl ๐
ohhh ok never used persistentDataPath on webgl yet sorry
one thing, use Path.Combine to make your filepath
remove / when doing this ^ cause it adds them for you
got it
so I have to use playerprefs if I want to save data on webgl?
Is there a way that works for both webgl and PC?
they both work
or do I need to somehow figure out in the code which build is running?
what you have should work for all platforms
persistent datapath takes care of that
it doesnt work on webgl, both local and when I upload to itch
Is my code correct tho?
is your browser set to clear user data?
it shouldnt
also Debug.Log inside your webgl
indexdb is saved locally by the browser if set up correctly
Does anyone have any good learning material to explore classes a bit more? As I understood at the beginning of a script "using xyz" allows the script to access a library and thus a set of tools/built in methods unique to that library that otherwise the computer wouldn't understand what you are asking of it. But then there's MonoBehavior which is a class that your newly created class inherits from which...appears to do something similar to what I thought "using libraries" did? Access to additional methods/tools unique to the MonoBehavior class? I know this is probably programming 101 stuff but I want to understand that relationship further. I'm guessing because I started in the context of interacting with unity that some more fundamentals were brushed over since the unity engine deals with that stuff for you.
pretty much (Namespaces) where the scripts/class is located , think of them as Grouping scripts together
Monobehavior class itself has properties and methods that are inherited from their parent class
You're wrong about accessing libraries.
The only thing using does is let you omit the namespace part of the class name
You don't need using statements at all
using statements 'import' namespaces which contain classes, Monobehaviour is a class in the UnityEngine namespace
You could write for example UnityEngine.GameObject and System.Collections.Generic.List all over your code. You wouldn't need using directives at all if you do that
The using directives just let you... not have to do that
you could say it exposes the contents of a namespace
: MonoBehaviour makes your class derive from the MonoBehaviour class. It's a completely different concept
you could say you were declaring you were going to use the contents ๐คจ
So the webgl still doesnt save/load data with my code above(localstorage)
indexDB/idbfs doesnt have my data
do you get errors in the web developer console?
webgl developer console? Do you mean in the browser console?
also Debug.Log(Application.persistentDataPath) make sure its going where you think it is
yes thats browser console
yes
ok I think I understand. I'll have to look up namespaces a bit more then. thanks for the feedback
It doesnt call "LoadGame" because it cant find the file
Looks like you've got some CORS errors
But thats for unity cloud?
what is 'Game Saved 0' ?
/idbfs/3fa30eb70475efdc120a28c777ab1461/Gold.json
so check local storage in browser
Pretty sure for webgl you have to read/write with UnittWebRequest not System.IO
I could be mistaken
Do you mean indexed DB?
no, system.IO works fine
yeah the learn to code doesn't seem to go over classes too much. Is it right to say then that monobehavior is the parent class for pretty much all new scripts created in the unity engine by default? or is parent class something more than just the class from which another inherits?
so its saving?
notice how it is saved per domain
It's the parent class you inherit from when you want to make a component (aka a thing you attach to a GameObject)
you only need to select url not folder
i think, unless you made that FILE_DATA
