#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 127 of 1

swift crag
#

Or you could just use the character controller's isGrounded property

#

no, there was not

short hazel
#

Type or namespace name

swift crag
#

but I suspect that you're missing a carManager class

quick edge
#

Ok thanks

#

That's really strange

swift crag
copper magnet
swift crag
#

You should combine your velocities together and move once

quick edge
#

You mean the playerVelocity and the direction ?

swift crag
#

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!

fierce shuttle
copper magnet
#

yep thats my guess as well

quick edge
swift crag
#

you still experience gravity when on the ground

quick edge
#

Yes but if I do that the gravity keep increasing

swift crag
#

Set it to zero if you're grounded!

sacred orbit
swift crag
#

so, every frame, you'll do this

quick edge
#

Ok

sacred orbit
swift crag
#
if (controller.isGrounded)
  gravityVelocity = Vector3.zero;

gravityVelocity += Vector3.down * Time.deltaTime * 9.8f;
...
sacred orbit
#

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);
    }
swift crag
#

The controller's job is to figure out how to move without going through walls

#

It's okay to constantly "push" into the ground

sterile radish
#

how would i go on about checking if the player has bought a specific item using this approach?
https://hastebin.com/share/ifafocikaj.csharp

swift crag
#

also, if this is on a game object that's getting deactivated, that will kill all coroutines on all components on the object

sacred orbit
#

The code is running, I Wanted to ask why the StopCoroutine isn't working

#

my brain forgot to specify lmao

quick edge
#

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 ?

sacred orbit
swift crag
quick edge
#

Oh okay

swift crag
#

in every place you call Move right now, replace it with something like

#
totalVelocity += moreVelocity;
#

then call controller.Move(totalVelocity); at the end

sacred orbit
swift crag
#

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

sacred orbit
#

so this should work, correct?

StopCoroutine(IEnumerator warningTextCoroutine());
#

because I used IEnumerator

swift crag
#

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

swift crag
#

You could also do this, though

#
private IEnumerator theEnumerator;

void Foo() {
  StopCoroutine(theEnumerator);
  theEnumerator = Bar();
  StartCoroutine(theEnumerator);
}
#

this seems more awkward, though

swift crag
#

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

swift crag
sacred orbit
#

ooooh ok

swift crag
sacred orbit
#

sorry, I started using C# only a few days ago so I'm quite new to this

swift crag
#

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

sacred orbit
#

so with this code:

#

stopcoroutine doesn't work

swift crag
#

StopCoroutine(warningTextCoroutine(text1))

This would try to stop a coroutine you never even started.

quick edge
#

This is more readable

sacred orbit
#

yes

quick edge
#

Ok

swift crag
#

Running warningTextCoroutine(text1) executes that method until it hits a yield, then it stops

quick edge
#

This was optimisation, not a solution to my problem right ?

swift crag
quick edge
#

Oh ok nice

#

Thanks either way

sacred orbit
#

the coroutine starting is based on input

quick edge
#

So in general I shouldn't move in two seperate occasions ?

sacred orbit
#

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

swift crag
#

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

sacred orbit
#

ooooohhh I just assumed Coroutines worked in a similar way to functions but I guess they don't

summer stump
swift crag
#
StartCoroutine("Foo");
StartCoroutine("Foo");
StartCoroutine("Foo");
StopCoroutine("Foo");

This would stop one of the three coroutines.

#

I never use string names, personally

summer stump
sacred orbit
#

so could I just use StopAllCoroutines()?

swift crag
slender nymph
swift crag
terse raven
#

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

swift crag
#

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.

swift crag
#

they have nothing to do with each other

#

if I call Foo() a fourth time, I get a fourth, completely new enumerator

swift crag
#

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

terse raven
#

hmmm, I have no idea how I'd go around that

swift crag
#

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

terse raven
#

no worries I'll have a look

sacred orbit
swift crag
#

where normal comes from a raycast

swift crag
#

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

sterile radish
#

how would i go on about checking if the player has bought a specific item using this approach?
https://hastebin.com/share/ifafocikaj.csharp

uncut dune
#

Where do you want to check it?

#

In that script itself

sterile radish
#

would it matter?

uncut dune
#

Just do

#

bool bought;

#

Qnd set it to true in the place it gets sold

lavish roost
#

Where or how are your specific items saved

sterile radish
#

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)

uncut dune
uncut dune
lavish roost
#

Well i mean he has to have an Item list of some sort and if not i recommend adding one

sterile radish
uncut dune
#

You could ads an unityevent to that one item

#

And u can still use that same script foe the other items

sterile radish
uncut dune
#

Like the effects of the items each one of them has the script that gives them the effect you want right?

sterile radish
uncut dune
#

That holds that script

lavish roost
#

Yup

uncut dune
#

Then you assign the object you wanr to it

lavish roost
#

Make an object of item with name, cost, etc

uncut dune
#

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

sterile radish
#

okay and i do this all in a seperate script right?

uncut dune
#

Have you ever used unity events?

sterile radish
sterile radish
uncut dune
#

Ok so go to the script you sent

lavish roost
#

You assign the Script to your Items in the scene

uncut dune
#

And write public UnityEvent eventWhenBought;

true pasture
#

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?

uncut dune
#

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

slender nymph
uncut dune
#

A public function that applies the buff

sterile radish
#

but all my items have the same script

uncut dune
#

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

true pasture
slender nymph
#

assign null on the line you declare it on

#

and don't forget to null check it in your anonymous method

uncut dune
sterile radish
#

okay i will send in a sec

#

thank you so much for your help btw! ๐Ÿ™

true pasture
#

oh thanks, I though I tried that, maybe i did var tween = null instead of Tween tween = null

uncut dune
sterile radish
sterile radish
#

yo wait this is so useful

#

i can literally do this with any item i want

#

thank you bro ๐Ÿ™ ๐Ÿ™

uncut dune
#

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

sterile radish
#

true

uncut dune
#

So no need gor as manny varia les

uncut dune
#

Because where you want to make the event be called

#

So when u buy the item

#

You have to put

#

eventWhenBought.Invoke();

uncut dune
sterile radish
#

or does it just buff it automatically?

uncut dune
#

So whatever you put in the function you assigned

#

Will run again

#

So yes

sterile radish
#

ah okay

#

and do i put the evnt on the item being buffed or the item that is going to the buff it?

sterile radish
uncut dune
uncut dune
sterile radish
#

oh wait

#

i invoke it in the Buy function right?

uncut dune
#

Where you buy the item

#

Where tou subtracted the money

sterile radish
#

yeah

uncut dune
#

Also have you assigned the event on the inspector?

sterile radish
#

yes

uncut dune
#

Ok then it should qork

sterile radish
#

i feel like im doing something wrong tho

#

i assign the evnt on the item that is going to buff the other one right?

deep bear
#

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?

swift crag
#

How are you rendering cards?

#

Are the sprites, or are they images in a canvas?

deep bear
#

They're just images on a canvas

timber tide
#

if they are transparent then you can use the rendering queue

swift crag
#

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

timber tide
#

but Fen's solution is usually what you'd do

deep bear
swift crag
#

I'm not sure how I'd do that.

#

(in a nice way, that is :p )

deep bear
#

Haha yeah, I was thinking it was a bit janky ๐Ÿ˜…

#

I might honestly just ditch the layout group and manually change their position

swift crag
#

you could display another copy of the card on top of the original, maybe

#

you would make it non-interactable

deep bear
#

Oh damn not a bad idea at all.

timber tide
#

yeah make a placeholder card

#

I do something similar with drag elements

opaque kettle
#

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.

deep bear
#

Awesome! I'll give that a shot, thanks everyone!

wraith mango
#

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

verbal dome
#

Note that the euler angles that you see in the inspector are not always the same as the value that eulerAngles gives you

wraith mango
#

okay

#

one seconnd

wraith mango
small mantle
#

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); }

verbal dome
verbal dome
#

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

muted wadi
#

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);
}```
small mantle
#

How would I use Vector3.SignedAngle in my case?

verbal dome
#

And ofc you need to store transform.forward in lastFrameForward after the calculations

#

Does that make sense?

small mantle
verbal dome
#

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

small mantle
#

It seems like it only checks when the object reaches a 360. Is this true?

verbal dome
#

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

true pasture
#

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

small mantle
#

You use lastFrameForward, what can I use instead? And what is it?

sharp jay
true pasture
#

if its null how could acess it earlier?

sharp jay
#

A null tween is still a "myTween"

#

it's just empty.

verbal dome
#

@small mantle

#

You need to store it in a variable in your class

true pasture
#

its definitely running the switch statement with the correct case

sharp jay
#

depends if the incomming case is correct.

small mantle
small mantle
verbal dome
#

Not sure why you put Vector3.forward there

tender breach
#

How do I assign a variable to only one clone instead of all of them?

small mantle
verbal dome
#

var obj = Instantiate(prefab);
obj.myVariable = 123;

flat slate
#

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

small mantle
sacred orbit
#

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?

verbal dome
#

So that you "remember" your last forward direction

verbal dome
small mantle
hidden citrus
#

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

sacred orbit
tender breach
sacred orbit
#

but I doubt I can define arrays that way

verbal dome
small mantle
# verbal dome Yep

This? ```
float angleDiffY = Vector3.SignedAngle(lastFrameForward, transform.forward, Vector3.up);

    lastFrameForward = transform.forward;```
sacred orbit
#

I don't know how I can define arrays like that

verbal dome
small mantle
verbal dome
sacred orbit
true pasture
#

are lists of tweens not allowed? its always a null list apparently? I declared it like this

sacred orbit
#

thank you

verbal dome
#

Didn't you want to track your rotation over time?

small mantle
slender nymph
verbal dome
#

Can you post the full script in a paste site?

small mantle
ionic zephyr
#

Could someone define Exit Time?

small mantle
verbal dome
small mantle
#

@verbal dome ```cs void Update() {
float angleDiffY = Vector3.SignedAngle(lastFrameForward, transform.forward, Vector3.up);

    lastFrameForward = transform.forward;

    print(angleDiffY);
}

void FixedUpdate() {
RespondToBoost();
RotatePlayer();
}

verbal dome
verbal dome
#

Though I would probably put it in fixedupdate

lavish tinsel
#

hi, I have an editor question. Is this the correct channel to ask?

north kiln
small mantle
verbal dome
muted wadi
small mantle
north kiln
verbal dome
# small mantle Yes

Try moving the code from Update to FixedUpdate, after RotatePlayer
Also print(angleDiffY * 1000) to see if it's just a really small number

north kiln
lavish tinsel
#

I'm a bit confused by the following:

  • if I reference a scriptable object, like PlayerScoreManager in a prefab - I'm not able to drag and assign a scene object of ScoreManager
  • 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

swift crag
north kiln
# north kiln Just not scaling by deltaTime at all?
- 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

verbal dome
#

Or... Your transform.forward is actually up or something?

small mantle
verbal dome
#

I mean, it is

#

You should've mentioned that tbh

muted wadi
verbal dome
#

And, if you just posted the rest of the script like I asked then I would've noticed it @small mantle

north kiln
small mantle
verbal dome
verbal dome
#

Because that's the "up" direction in this case, I assume

#

It's top down perspective, right?

small mantle
#

It's printing huge numbers up to 1000+

verbal dome
#

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

small mantle
verbal dome
#

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

small mantle
verbal dome
#

And instead of storing the transform.forward in the variable, use rb.rotation instead

#

If you did everything I just said then it works

small mantle
verbal dome
#

Check what?

#

You add the angleDiffY to a float variable.

ancient island
#

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)
verbal dome
#

@small mantle When that float goes below -360 or 360, you have performed a back/frontflip. Use an if statement

small mantle
verbal dome
twin bolt
#

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.

small mantle
verbal dome
#

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

verbal dome
#

if(totalAngle < -360f) Debug.Log("Sick backflip bro");

ancient island
small mantle
verbal dome
#

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

small mantle
verbal dome
#

It should be zero by default, of course.

small mantle
small mantle
verbal dome
#

Yes, or decrease, depending on which way your rotate.

#

When you hit the ground you want to set it to zero again

small mantle
verbal dome
#

(Please tell me it makes sense now)

true pasture
#

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

small mantle
twin bolt
#

Question, would setting the cameras position every frame, to be with the player, be better than it being as a child of the player?

muted wadi
twin bolt
muted wadi
#

are you sure there is actually jitter happening because it could be your computer

twin bolt
muted wadi
#

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

summer stump
#

What is the -1 supposed to do here, in your own words?

Edit: oh, it's gone

summer stump
muted wadi
#

also from my understanding the -1 is the layer ID for the layermask that it's targeting, and -1 means all layers

sterile radish
muted wadi
summer stump
muted wadi
#

ah i see

#

i guess for my level of use right now it might as well mean everything

summer stump
muted wadi
summer stump
radiant sail
#

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
summer stump
#

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

teal viper
#

No, I think -1 is might actually be correct. Due to how negation works in C# and most other programming languages(2's complement).

summer stump
muted wadi
#

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

radiant sail
#

anybody know how i can add a offset rotation to the transform.LookAt method

rocky canyon
#

just add the offset to the (thing ur lookin at's transform)

#

LookAt(theThing.transform.position + new Vector3(0,0,0))

eternal needle
rocky canyon
#

or afterwards, yea.

teal viper
summer stump
tender breach
#

How do I respawn pieces in a falling block game after they hit the ground?

radiant sail
robust condor
#

@tender breachMove them or Destroy and Instantiate new ones?

north hawk
#

Guys i need playfab

#

Can u give playfab

summer stump
arctic harbor
#

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

robust condor
#

@arctic harborUse events

verbal dome
radiant sail
verbal dome
#

Multiplying by that Quaternion.Euler is what "adds" to the rotation

radiant sail
#

Ok Ty

#

i put that in the update replacing the lookat right?

verbal dome
#

Or if it's simpler for you, first do LookAt normally, then transform.Rotate after that

eternal needle
twin bolt
#

Question, if i set the players cameras position to the body, should i use update or something different?

twin bolt
modest current
#

Why does unity error when It cant find a key in a dictionary?

twin bolt
#

Now i have one issue, the player is moving, but it doesnt take in account of the cameras rotation, how do i fix this?

arctic harbor
# robust condor <@187064746376298499>Use events

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

verbal dome
modest current
prisma blaze
#

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

summer stump
robust condor
#

@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

twin bolt
#

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);```
verbal dome
twin bolt
#

Oh, how can i fix this then?

verbal dome
#

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)

twin bolt
#

Well my issue is not rotating the player, its about moving in the same direction of the camera.

verbal dome
#

Ok well I didn't talk about rotating the player at all

verbal dome
#

If you do that then get rid of cameraForward

twin bolt
#

so transform.rotation = Quaternion.Euler(0, playerCamera.transform.eulerangles.y, 0)
?

verbal dome
#

Nah, make a new Quaternion out of that

#

Then multiply moveDirection with that quaternion to rotate moveDirection

#

Hmm wait

twin bolt
#

What will that quaternion go into then?

verbal dome
#

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

twin bolt
#

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.

verbal dome
#

I don't think anything here would cause a delay

modest current
verbal dome
twin bolt
arctic harbor
modest current
#

It might be too complicated

verbal dome
#

Oh god is this that voxel thing you showed yesterday

modest current
#

yeah it's really frustrating that I cant just check if the xyz index exists that would solve all my problems

verbal dome
#

As suggested, you could just use a single Dictionary with Vector3Int as the key

tribal zephyr
small mantle
#

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; } }

teal viper
# modest current

If you keep these implementation, you'd need to call TryGetValue on every single dictionary in that chain.

tribal zephyr
robust condor
#

@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?

boreal tangle
#

does someone know whats the point of skinWidth in creating a player controller using translate?

verbal dome
arctic harbor
#

Hmm. It's just a simple platformer

rich adder
teal viper
boreal tangle
#

I meant making a player controller using translate

arctic harbor
#

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

rich adder
boreal tangle
#

I do but I have seen people say it allows more control and I can use ray cast to do collisions

rich adder
#

probably not worth doing it with translation

boreal tangle
#

I wanna at least try. If it gets to tedious il go back to physics

teal viper
#

And what makes you think that there's any point at all?

boreal tangle
#

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.

rich adder
#

there are better ways to fix getting "stuck"

boreal tangle
#

I'm only using it because the tutorial is

rich adder
#

๐Ÿคทโ€โ™‚๏ธ sounds like a poor tutorial

teal viper
#

Nor did you explain what object does the skinWidth property belong to.

#

Or any other info about your setup.

boreal tangle
#

So would it be better to just use physics?

rich adder
#

usually that can be fixed with step height/ skin or also the Physics settings

boreal tangle
#

The problem wasnt getting stuck. I was just confused about what skinWidth was and its purpose when I was following the tutorial.

teal viper
#

What class/type does this property belong to? Can you answer that one question?

#

What skinWidth are you talking about?

arctic harbor
meager gust
#

also like other people have said, stop using translate if you want any form of collision

#

you're looking for CharacterController.Move()

boreal tangle
#

whats wrong with just raycasting

meager gust
#

for movement?

boreal tangle
#

for collisions

meager gust
#

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

teal viper
boreal tangle
#

ok I get it. But do you think unity's physics can make movement on par to platformers like hollow knight or celeste?

teal viper
#

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.

meager gust
#

which is used by most of the gaming industry

teal viper
#

The movement part is up to you.๐Ÿ‘†

boreal tangle
#

ok Thank you

rich adder
meager gust
#

yes

rich adder
boreal tangle
#

ok ty

robust condor
#

@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
    }
}
modest current
#

How come c# wont allow you to modify a dictionary while iterating over it?

robust condor
#

Race conditions?

meager gust
robust condor
#

@meager gustElaborate

meager gust
#

Race conditions generally involve threads. Updating a dictionary value invalidates the iterator

verbal dome
arctic harbor
modest current
glass urchin
#

So, if I want an animation to start a specific frame, how do I do that?

eternal needle
meager gust
#

iterate the list, and mess with the dictionary while you're doing it

rich adder
#

u can just loop thru the kvp

meager gust
#

it wouldn't let him

rich adder
#

you need a list like you said, iterate thru keys

modest current
#

I'm trying to change and remove some values of my voxel data

eternal needle
#

yea makes sense, you're trying to add values to the keys while iterating through it

modest current
#

Only reason it doesn't work but I'm trying to understand how I can possibly get around this

#

maybe different type of loop

meager gust
# modest current

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

tender breach
rich adder
#

also mixing physics and translate = bad

tender breach
#

I want the gameObject to spawn once via OnTriggerEnter2D, but it spawns mulitple times.

rich adder
tender breach
#

No, only once

tender breach
#

Didn't you read the code?

rich adder
#

OnTriggerEnter is a one frame event

#

also what bawsi said

tender breach
eternal needle
#

i really wasnt expecting that as an answer

summer stump
# tender breach No

You set it to true and immediate check if it is true.

You see no issue with that?

summer stump
eternal needle
#

then maybe take a break from unity and do some basic c#

rich adder
#

why did you put that there then

summer stump
tender breach
#

So what should I change the code to?

rich adder
#
if(!spawn){
spawn = true;
//etc..```
summer stump
tender breach
#

Oh

#

How do I do that?

robust condor
#

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

rich adder
teal viper
tender breach
#

I'm trying to spawn a gameObject only once when Spawn = true.

rich adder
#

also don't forget code runs from top to bottom

teal viper
tender breach
#

When it touches OnTriggerEnter2D

rich adder
#

defeats the whole purpose of a bool

unborn moon
#

lol, the code have too many if condition

teal viper
unborn moon
#

it makes me remember the guys who did yandere simulation

twin bolt
#

What would you guy's say is the best method of crouching for 3d First person games?

rich adder
#

shrink the collider/move the center. done

rocky canyon
#

move the world upwards

summer stump
twin bolt
#

My setup is very janky

rich adder
teal viper
#

Fix the setup then

twin bolt
#
        {
            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);
        }```
rocky canyon
#

Cinemachine

summer stump
rocky canyon
#

        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));
            }
        }```
twin bolt
#

I'm doing it here, but it goes very slow, and doesnt stop at 1.77

rocky canyon
#

else move ur height, and ur center the camera (if parented) should follow along

#

but cinemachine fr

twin bolt
#

I had the camera as a child before, but had to remove it because of jitter, so now i have to move it manually.

rocky canyon
#

does it pretty smoothly

twin bolt
# rich adder prob wrong lerp

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);
    }```
rocky canyon
#

but theres still a bit of jerk.. but its very subtle

rich adder
rocky canyon
#

i was young

#

havent revised it any since then

rich adder
#

fair enuf haha

rocky canyon
#

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

rich adder
rocky canyon
#

but ya, if i were to do it again id just do some proper lerps

rich adder
#

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...

โ–ถ Play video
twin bolt
#

Would translate be bad to use.

summer stump
sterile radish
rich adder
#

I would personally use Ink instead of building my own

rocky canyon
#

you'd have to make a couple more lists, one of responses, and another for the response to ur response..

sterile radish
#

whats lnk?

rocky canyon
#

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

rich adder
verbal dome
rich adder
#

ah yes ink not lnk

sterile radish
#

okay ill check it out

#

thanks!

rocky canyon
#

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...

โ–ถ Play video
#

heres a video that implements Ink

rich adder
#

this guys video helped me greatly

#

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...

โ–ถ Play video
rocky canyon
#

mobile dev, here i come ๐Ÿ™‚

#

was waiting til i got a phone with a gyro

#

christmas provided

rich adder
#

android is dumb easy, IOS not soo much esp if you're on an old mac with old xcode

rocky canyon
#

ah, thankfully im windows, xbox, and android

rich adder
#

I'd love to get myself some VR for development ๐Ÿ˜ฎ

rocky canyon
#

AR seems like it could be cool

#

still pretty early.. time to get ur foot in the door with something

rich adder
#

yeah esp the face topology stuff / filters

twin bolt
#

How do i make .movetowards not infinitely move, and stop at the target point.

rocky canyon
#

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

twin bolt
#

How do i scale a object from its pivot from a script?

timber tide
#

transform.scale

#

actually it may just be localscale

twin bolt
#

oh so it works automatically?

#

Okay i'll try it.

timber tide
#

uh, if you consider setting it via script is automatic

#

unless you mean by transform handling matrix transformation then sure

amber spruce
#

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

summer stump
amber spruce
#

how do i reference the player to it

summer stump
sacred orbit
#

does anyone here know anything about git for collaboration in unity?

summer stump
sacred orbit
#

cool, I have a super specific question

wintry quarry
#

Lots of people know lots of things. If you have a question, ask it

cunning rapids
sacred orbit
#

if I want to merge two branches on git, is it possible to combine the additions on both branches when merging?
For example:

radiant sail
sacred orbit
#

???? I looked it up but it said that it just overwrites what is on the branch

wintry quarry
#

Not sure where you read that

cunning rapids
wintry quarry
#

it's called "merge" for a reason

radiant sail
cunning rapids
radiant sail
#

it works fine now so ye

sacred orbit
# wintry quarry Not sure where you read that

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?

amber spruce
#

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

wintry quarry
#

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.

amber spruce
cunning rapids
# radiant sail yes

You can just set the rotation of the instance directly when you Instanciate it

radiant sail
sacred orbit
wintry quarry
#

when you merge it will create a merge commit

#

if you don't like the results you can just roll back that merge commit

wintry quarry
#

Do note that whenever you merge there's the chance for conflicts

cunning rapids
#
public Transform FirePoint;

//some shi here

Instantiate(Prefab, FirePoint.position, FirePoint.rotation);

@radiant sail

sacred orbit
# wintry quarry Are these commits? Yes.

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?

wintry quarry
#

what does E without C mean

sacred orbit
#

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

cunning rapids
wintry quarry
cunning rapids
sacred orbit
radiant sail
#

ok

sacred orbit
#

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?

wintry quarry
#

Wait now we're talking about files? I thought we were talking about commits

sacred orbit
wintry quarry
wintry quarry
sacred orbit
#

just didn't remove it

cunning rapids
# radiant sail ok

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

wintry quarry
#

You need to think in terms of commits, not files.

radiant sail
amber spruce
cunning rapids
robust condor
#

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

queen adder
#

coroutine update pattern looks cleaner, is it not?

#

easy timers

wintry quarry
#

If that matters in your game.

queen adder
#

isnt waitforsecond timing things well?

#

like 100x of waitfor5sec is almost very very very close to 500 seconds perfect?

wintry quarry
#

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

queen adder
#

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

wintry quarry
queen adder
#

WaitForSeconds(animdelay - lastdeltaTime)

wintry quarry
#

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

queen adder
#

right yea

wintry quarry
#

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

amber spruce
#

whats the best way to add every gameobject that has the layer Player to a list

slender nymph
#

for what purpose

amber spruce
#

so i can reset there posistion

slender nymph
#

that's not very descriptive at all

amber spruce
#

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

slender nymph
#

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

wintry quarry
#

just add them to the list as you spawn them

amber spruce
#

the list is on a object in the new scene

slender nymph
#

or have them subscribe to the onSceneLoad sceneLoaded event and reset their positions themselves

wintry quarry
#

pass the list to the second object as needed

amber spruce
#

ok thanks

robust condor
#
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

slender nymph
#

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

robust condor
#

Half the screen down from cursor

slender nymph
#

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?

robust condor
#

But the Y is up?

slender nymph
#

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

robust condor
#

I need it to spawn on 0 on the Y axis

gaunt ice
#

is the camera orthogonal or perspective?

robust condor
#

Ortho

slender nymph
gaunt ice
#

oh you have said that, i overlook it, btw 2d game is x-y plane by default

slender nymph
# robust condor I need it to spawn on 0 on the Y axis

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

summer stump
# amber spruce so i decided to use findobjectoftype and my player is a clone of a prefab so wou...

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

robust condor
slender nymph
#

the red dot is your cursor, yes?

robust condor
#

Yep

slender nymph
#

and 0 on the Y axis is where that block is located, yes?

robust condor
#

I assume so

slender nymph
#

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

robust condor
#

It looks like this if I spawn it on the cursor

north kiln
#

so you need to set the Z coordinate

slender nymph
robust condor
#

I guess I need a two step solution. Because I only want it to move after the cursor on X and Z axis

slender nymph
#

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

sacred orbit
#

what is the best way to collaborate on a unity project at the same time?

slender nymph
#

git

charred spoke
#

git

sacred orbit
#

wouldn't that cause alot of conflicts?

slender nymph
#

how so?

charred spoke
#

Only if you fail to use git correctly

sacred orbit
#

I just tried it out, different additions to scenes will cause conflicts

slender nymph
#

yes, do not work on the same files at the same time

sacred orbit
#

when merging*

slender nymph
#

this is typical with any version control

charred spoke
#

Thats where conflict resolution comes in

sacred orbit
sacred orbit
slender nymph
#

if you mean working on the same files at the same time in real time, then no. learn how to properly use version control

charred spoke
sacred orbit
north kiln
charred spoke
#

Yep I was just about to mention the YAMLMerge

sacred orbit
north kiln
#

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

robust condor
#

How to check if Vector3 is 0,0,0?

slender nymph
#

just compare it to Vector3.zero

ivory bobcat
#

a == b

prisma blaze
#

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)

rich adder
prisma blaze
rich adder
prisma blaze
#

on the transparent cube, no colliders are hit

rich adder
#

should be at the feet anyway, why is it in his mid

prisma blaze
#

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

wintry quarry
#

The default capsule is 2m tall

prisma blaze
#

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

wintry quarry
prisma blaze
#

thanks for the help

hasty spire
#

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

wintry quarry
hasty spire
wintry quarry
#

Position

#
player.transform.position = otherObject.transform.position;```
hasty spire
#

right

#

and if i have a serialized field for the transform of the object can i just put that variable.position?

wintry quarry
#

Yes

#

Of course

hasty spire
#

is this the best way to do screen transitions?

wintry quarry
#

Screen transitions?

#

Wdym by that

hasty spire
#

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

wintry quarry
#

Is it the... Best way? I don't really know how to answer that

#

What do you mean by "best"?

hasty spire
#

nvm

unkempt thunder
#

Any good toturial to start programming in unity

rich adder
slender nymph
eternal falconBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

unkempt thunder
slender nymph
#

did you just stop reading at the first .?

unkempt thunder
rich adder
#

unity is just an api

gaunt ice
#

c# in unity different from c# outside a little bit btw

rich adder
languid spire
gaunt ice
#

also the async await part

rich adder
#

async and await work fine

#

Task.Delay has issues though well nvm that ๐Ÿ˜›

slender nymph
#

works fine for me, what do you mean it has issues?

rich adder
#

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 ๐Ÿ˜›

slender nymph
#

i will also note that i'm using 2023 with the Awaitable class

rich adder
#

Ohh

slender nymph
#

though i can test it again with a method that returns Task instead

rich adder
#

last time i did it was 2021 prob why. I will try my 2022

slender nymph
#

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?

static cedar
#

Task.Yield reduced my framerate.

#

Then I started using UniTask.

#

Works a lot better.

rich adder
#

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

slender nymph
#

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

rich adder
#

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 ๐Ÿ˜…

gaunt ice
#

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

rich adder
#

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

hollow zenith
#

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).

rich adder
#

lemme find the link

languid spire
#

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

hollow zenith
#

What do I do to use browser storage?
docs say to use Application.persistentDataPath, I guess that I cant use File.Write in webgl?

hollow zenith
#

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?

languid spire
rich adder
#

you can also just use local files anyway

hollow zenith
#

System.IO doesnt seem to work with webgl for me

#

Or maybe its json that doesnt work

languid spire
#

works for me

rich adder
hollow zenith
#
    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)

rich adder
#

this will not save to indexeddb

languid spire
#

yes it will

rich adder
#

it goes in your User/AppData/LocalRow

languid spire
#

not in WebGL

hollow zenith
#

I need it for webgl ๐Ÿ˜„

rich adder
#

ohhh ok never used persistentDataPath on webgl yet sorry

languid spire
#

one thing, use Path.Combine to make your filepath

rich adder
#

remove / when doing this ^ cause it adds them for you

hollow zenith
#

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?

rich adder
#

they both work

hollow zenith
#

or do I need to somehow figure out in the code which build is running?

languid spire
#

what you have should work for all platforms

rich adder
hollow zenith
#

it doesnt work on webgl, both local and when I upload to itch

#

Is my code correct tho?

rich adder
#

itch is tricky

#

idk if its the same afaik they recycled the machines

languid spire
#

is your browser set to clear user data?

hollow zenith
#

it shouldnt

rich adder
languid spire
#

indexdb is saved locally by the browser if set up correctly

gilded pumice
#

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.

rich adder
wintry quarry
#

You don't need using statements at all

languid spire
wintry quarry
#

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

languid spire
#

you could say it exposes the contents of a namespace

wintry quarry
#

: MonoBehaviour makes your class derive from the MonoBehaviour class. It's a completely different concept

north kiln
#

you could say you were declaring you were going to use the contents ๐Ÿคจ

hollow zenith
#

So the webgl still doesnt save/load data with my code above(localstorage)

#

indexDB/idbfs doesnt have my data

languid spire
hollow zenith
#

webgl developer console? Do you mean in the browser console?

rich adder
#

yes thats browser console

hollow zenith
#

None as far as I can see

gilded pumice
#

ok I think I understand. I'll have to look up namespaces a bit more then. thanks for the feedback

hollow zenith
#

It doesnt call "LoadGame" because it cant find the file

wintry quarry
#

Looks like you've got some CORS errors

hollow zenith
#

But thats for unity cloud?

languid spire
#

what is 'Game Saved 0' ?

hollow zenith
rich adder
#

so check local storage in browser

wintry quarry
#

Pretty sure for webgl you have to read/write with UnittWebRequest not System.IO

#

I could be mistaken

hollow zenith
gilded pumice
rich adder
#

so its saving?

hollow zenith
#

doesnt seem like it

#

its empty

languid spire
#

notice how it is saved per domain

wintry quarry
rich adder
#

i think, unless you made that FILE_DATA