#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 497 of 1

upper thistle
#

Will try it rn

rocky canyon
#

if u want to teleport ur character controller ur gonna need to do a work-around..

#

disable it first.. then move it then re-enable it

upper thistle
slender nymph
#

(Try)GetComponent

rocky canyon
#

GetComponent if u have the object

upper thistle
#

Yeah, the object is under something else I already tried that

rocky canyon
#

u have the player gameobject..

slender nymph
#

or since you are serializing a reference to the object already, just reference that component directly instead of referencing its gameobject

rocky canyon
#

player.GetComponent<CharacterController>();

upper thistle
rocky canyon
#

tf is even that?

slender nymph
# upper thistle

there are beginner c# courses pinned in this channel. start there instead of randomly guessing

upper thistle
#

the assigned object

rocky canyon
#

myController = thePlayer.GetComponent<CharacterController>();```
#

or what box was saying was just use the CharacterController..

#

public Transform teleportTarget;
public CharacterController thePlayer;

rocky canyon
#

yup, its always better to assign things by the Type ur wanting to use

#

instead of using GameObject.. b/c then ur gonna just have to grab all the components off of that gameobject anyway

#

if u have a component directly.. its always easy as theComponent.gameObject; <- to get the actual gameobject

lofty lintel
#

Guys how would I get exact position of this stick? I think with script im getting like world cordinants

CachedXPos.Clear();
foreach (var stick in StickUIs)
{
    CachedXPos.Add(stick.transform.position.x.);
}
for (int i = 0; i < CachedXPos.Count; i++)
{
    Debug.Log($"stick.{i} - {CachedXPos[i]}");
}
upper thistle
#

I can reference directly off of it with the main controller

#

thank you

lofty lintel
rocky canyon
#

world coordinates are the exact position tho..

lofty lintel
#

don't need it

#

I think I can still do it without raycast xd

#

Coz raycast confuses me a lot...

#

gonna do it hard code way xdd

rocky canyon
#

u could always save the positions uve spawned things at before..

lofty lintel
#

thats what im doing

rocky canyon
#

and then loop thru that collection.. when spawning a new one

rocky canyon
lofty lintel
#

trying to do I guess...

rocky canyon
#

gotta try first ๐Ÿ™‚

lofty lintel
#
SpawnPos = new Vector3(randomXPos, randomYPos, 1);

foreach (var stick in StickUIs)
{
    //x - 9
    //x2 - 0
    while (randomXPos >= stick.transform.localPosition.x - 10f || randomXPos <= stick.transform.localPosition.x + 10f)
    {
        randomXPos = UnityEngine.Random.Range(minX, maxX);
        SpawnPos.x = randomXPos;
        foreach (var x in CachedXPos)
        {
            if (randomXPos >= x - 10f || randomXPos <= x + 10f)
            {
                randomXPos = UnityEngine.Random.Range(minX, maxX);
                SpawnPos.x = randomXPos;
            }
            else
            {
                break;
            }
        }
        if (randomXPos <= stick.transform.localPosition.x - 10f || randomXPos >= stick.transform.localPosition.x + 10f)
        {
            Debug.Log("Stick Should've spawned at right place."); 
            
            break;
        }
    }
}```
Look at this code mosntracity
quick pollen
#

So, here's an issue I have
I'm trying to implement a "lock on" system, where, whenever you press Q, your character starts always facing the current enemy
The issue: the way I handle diagonal strafing without lock-on is by using offsetting the direction the character is facing to make it go diagonally. This is fine in itself, but I don't know how to implement the same thing in the lock-on mode, and all attempts have gone pretty bad so far.

rocky canyon
rocky canyon
#

not dangerous ๐Ÿ˜„

lofty lintel
#

haha

quick pollen
#
        offset.z = walking? 1f : 0f;
        offset.y = 1f;
        if(inputVectorRaw.x != 0 && inputVectorRaw.y != 0){
            offset.x = -(inputVectorRaw.x * inputVectorRaw.y);
        } else offset.x = 0;
        
        cameraDirection = cameraTransform.rotation * offset;
        cameraDirection.y = 0;
        if(lockedOn){
            Quaternion targetRotation = Quaternion.LookRotation(enemy.transform.position - transform.position - new Vector3(0, enemy.transform.position.y - transform.position.y, 0f));
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime));
        } else if(!lockedOn && cameraDirection != Vector3.zero && !animator.GetCurrentAnimatorStateInfo(0).IsTag("Attack")) //if the direction is valid and the player isn't attacking
        {
            Quaternion targetRotation = Quaternion.LookRotation(cameraDirection);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime)); //Pow enhanced wrong lerp for smooth turning
        }```
#

(edit for clarity)

rocky canyon
quick pollen
#

okay let me simplify it a bit then

lofty lintel
#
    private List<float> CachedXPos = new List<float>();
    private Vector3 SpawnPos;

float minX = StickSpawn.position.x - 9f;
  float maxX = StickSpawn.position.x + 9f;
  float minY = StickSpawn.position.y - 1f;
  float maxY = StickSpawn.position.y + 1f;
  float randomXPos = UnityEngine.Random.Range(minX, maxX);
  float randomYPos = UnityEngine.Random.Range(minY, maxY);
  if (StickUIs.Count == 0)
  {
      SpawnPos = new Vector3(randomXPos, randomYPos, 1);
      CachedXPos.Add(SpawnPos.x);
  }
  else
  {
      SpawnPos = new Vector3(randomXPos, randomYPos, 1);

      foreach (var stick in StickUIs)
      {
          while (randomXPos >= stick.transform.localPosition.x - 10f || randomXPos <= stick.transform.localPosition.x + 10f)
          {
              randomXPos = UnityEngine.Random.Range(minX, maxX);
              SpawnPos.x = randomXPos;
              foreach (var x in CachedXPos)
              {
                  if (randomXPos >= x - 10f || randomXPos <= x + 10f)
                  {
                      randomXPos = UnityEngine.Random.Range(minX, maxX);
                      SpawnPos.x = randomXPos;
                  }
                  else
                  {
                      break;
                  }
              }
              if (randomXPos <= stick.transform.localPosition.x - 10f || randomXPos >= stick.transform.localPosition.x + 10f)
              {
                  
                  
                  break;
              }
          }
      }
  }
StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));
Debug.Log("Stick Should've spawned at right place.");
CachedXPos.Clear();
foreach (var stick in StickUIs)
{
    CachedXPos.Add(stick.transform.localPosition.x);
}
for (int i = 0; i < CachedXPos.Count; i++)
{
    Debug.Log($"stick.{i} - {CachedXPos[i]}");
}```
#

Still not working...

#

Sticks should spawn atleast with distance of 10 on X axis :(

quick pollen
#
        if(inputVectorRaw.x != 0 && inputVectorRaw.y != 0){
            offset.x = -(inputVectorRaw.x * inputVectorRaw.y);
        } else offset.x = 0;
        offset.y = 1f;
        offset.z = walking? 1f : 0f;
        cameraDirection = cameraTransform.rotation * offset;
        cameraDirection.y = 0;
        if(lockedOn){
            Vector3 enemyDirection = enemy.transform.position - transform.position;
            Vector3 enemyDirectionMinusY = enemyDirection - new Vector3(0, enemy.transform.position.y - transform.position.y, 0f);
            targetRotation = Quaternion.LookRotation(enemyDirectionMinusY);
        } else if(cameraDirection != Vector3.zero)
            targetRotation = Quaternion.LookRotation(cameraDirection);

        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime)); //Pow enhanced wrong lerp for smooth turning```
#

@rocky canyon should be way better

twin bolt
#

How do i add gameobjects to a list by name at start? I have 30 different objects, that i need to put into a list, but doing it via the editor would take ages.

lofty lintel
#

maybe using tags?

rocky canyon
#

all good answers

quick pollen
#

for each gameobject with a specific tag, add it to a list

#

basically just convert that into code

twin bolt
#

I was trying to avoid adding tags because it would only be used once, but i'll just do it.

verbal dome
twin bolt
quick pollen
#

why not instantiate them then

twin bolt
verbal dome
#

Could also put them under the same parent, and on the parent have a script that loops through its children

twin bolt
quick pollen
#

also why is it that
Quaternion x;
is not equal to Quaternion.Euler(x * Vector.one);?

lofty lintel
#

Create gameobject in hierachy and

#

put all of them in that one

#

drag and drop

verbal dome
#

You mean someQuaternion.x?

quick pollen
#

x is just an arbitrary variable name

wintry quarry
quick pollen
#

let's say that x is the rotation of an object

#

which is already determined

wintry quarry
#

Because a Quaternion is not a set of euler angles no matter how much you want it to be.

lofty lintel
wintry quarry
#

And a direction vector is not the same as a set of euler angles either

#

Maybe you're looking for Quaternion.LookRotation?

quick pollen
quick pollen
wintry quarry
#

Please show an example of what you mean

wintry quarry
#

No Vector3 needs to be involved at all

eternal needle
quick pollen
#

perhaps I am approaching the issue wrong

quick pollen
wintry quarry
#
player.rotation *= Quaternion.Euler(0, 30, 0);``` for example
#

Assuming you mean y axis

quick pollen
#

Basically, I want to make it so whenever the player is strafing, it uses enemyDirection = enemy.transform.position - transform.position; in a Quaternion.LookRotation

#

so it just looks towards the enemy

wintry quarry
#

Ok what's the problem?

quick pollen
#

but when I'm strafing diagonally, I want to give it an offset

wintry quarry
#

Sharing your actual code etc would go a long way to a solution

quick pollen
#

so you can either approach or distance yourself from the enemy by pressing W/S

quick pollen
wintry quarry
#

Quaternion.LookRotation(...) * Quaternion.Euler(0, 30, 0)

#

For example

quick pollen
#
        if(inputVectorRaw.x != 0 && inputVectorRaw.y != 0){
            offset.x = -(inputVectorRaw.x * inputVectorRaw.y);
        } else offset.x = 0;
        offset.y = 1f;
        offset.z = walking? 1f : 0f;
        cameraDirection = cameraTransform.rotation * offset;
        cameraDirection.y = 0;
        if(lockedOn){
            Vector3 enemyDirection = enemy.transform.position - transform.position;
            Vector3 enemyDirectionMinusY = enemyDirection - new Vector3(0, enemy.transform.position.y - transform.position.y, 0f);
            targetRotation = Quaternion.LookRotation(enemyDirectionMinusY);
        } else if(cameraDirection != Vector3.zero)
            targetRotation = Quaternion.LookRotation(cameraDirection);

        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Mathf.Pow(turnFractionTurning, 100 * Time.deltaTime)); //Pow enhanced wrong lerp for smooth turning```
wintry quarry
#

enemyDirection.y = 0;

#

Instead of that crazy formulation

quick pollen
#

I can try

#

it did some crazy shenanigans last time I tried it

wintry quarry
#

Anyway there's no offset in this code

#

At least not when the enemy stuff is happening?

quick pollen
#

cameraDirection = cameraTransform.rotation * offset

#

in the enemy stuff I removed it because it was faulty

#

but I wanted the same thing that I had in the non-enemy stuff

wintry quarry
#

It's not clear what offset is or what cameraDirection is

quick pollen
#

cameraDirection is the direction the camera is facing

#

that way, whenever I press W, the character moves forward relative to where forward is from the camera

wintry quarry
#

I mean that I don't even know what data type they are or where the data came from

quick pollen
#

offset is a vector3

#

same for cameraDirection

lofty lintel
#
//generating random position
SpawnPos = new Vector3(randomXPos, randomYPos, 1);

foreach (var stick in StickUIs)
{
    //checking if position is compatebale with other sticks.
    while (randomXPos >= stick.transform.localPosition.x - 5f || randomXPos <= stick.transform.localPosition.x + 5f)
    {
        //if not change position
        randomXPos = UnityEngine.Random.Range(minX, maxX);
        SpawnPos.x = randomXPos;
        foreach (var x in CachedXPos)
        {
            //check if its alright with any other alreadySpawnedStick x positions
            if (randomXPos >= x - 5f || randomXPos <= x + 5f)
            {
                randomXPos = UnityEngine.Random.Range(minX, maxX);
                SpawnPos.x = randomXPos;
            }
        }
        //if its far enough.
        if (randomXPos <= stick.transform.localPosition.x - 5f || randomXPos >= stick.transform.localPosition.x + 5f)
        {
            break;
        }
    }
}```

```c#
StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));
//Debug.Log("Stick Should've spawned at right place.");
CachedXPos.Clear();
foreach (var stick in StickUIs)
{
    CachedXPos.Add(stick.transform.localPosition.x);
}
for (int i = 0; i < CachedXPos.Count; i++)
{
    Debug.Log($"stick.{i} - {CachedXPos[i]}");
}```
Couldn't get it working...
#

any ideas?

quick pollen
#

thank you very much!

verbal dome
quick pollen
#

I only have one more small issue

#

instead of turning backwards to the right, it does a 315 degree turn

lofty lintel
#

Sticks should spawn atleast with distance of 5 on X axis

lofty lintel
verbal dome
#

So those are UI objects on a canvas? And they have a RectTransform?

lofty lintel
#

yes

#

Couldn't get it done with raycasting as it really confuses me off how I would do it

lofty lintel
#

All i am trying to do is spawning those sticks atleast 5 float difference in distance on X axis

verbal dome
#

How big of a distance do you expect "5" to be?

#

I'm not sure but I think that localPosition is in pixels when dealing with UI

lofty lintel
#

wellI checked it too

#

This is exactly 5

lofty lintel
#

If I pick up more sticks this is how it ends up.

verbal dome
rocky canyon
#

just need a loop lookin for valid positions.. after x amount of attempts break out of the loop

lofty lintel
#

thats the difference im talking bout

verbal dome
#

Right. So what's the issue exactly? I don't see any stick that is closer to another stick than that

rocky canyon
verbal dome
# lofty lintel u do

I really don't, can you draw on it to point out which sticks are closer to each other than the first image you posted?

lofty lintel
quick pollen
# quick pollen

Anyone any ideas on how to not make it do that giant turn?

rocky canyon
verbal dome
#

All of these are further away than 5

lofty lintel
lofty lintel
#

not just one to another and another to another

verbal dome
#

They are though. They are just overlapping, is that the issue?

rocky canyon
#

if ur trying to space them out by 5 i would use 5 + the width and or height of the stick.. (soo u dont get overlapping at all)

lofty lintel
#

so Instead of getting this

lofty lintel
wintry quarry
lofty lintel
#

what is that

wintry quarry
#

An algorithm that distributes objects how you want

lofty lintel
#

well yeah but- that seems to complicated

#

i was just thinking of using collider-

#

but idk about UI and colliders, seems wrong

verbal dome
lofty lintel
verbal dome
lofty lintel
#

it's random

#

Im using like random X axis

#

but it should regenerate if its like not far enough

#
foreach (var stick in StickUIs)
{
    //checking if position is compatebale with other sticks.
    while (randomXPos >= (stick.transform.localPosition.x - 5f) || randomXPos <= (stick.transform.localPosition.x + 5f))
    {
        //if not change position
        randomXPos = UnityEngine.Random.Range(minX, maxX);
        SpawnPos.x = randomXPos;
        foreach (var x in CachedXPos)
        {
            //check if its alright with any other alreadySpawnedStick x positions
            if (randomXPos >= (x - 5f) || randomXPos <= (x + 5f))
            {
                Debug.Log($"{randomXPos} is inside the range |{randomXPos} >= {x -5f} or {randomXPos} <= {x+5f}|");
                randomXPos = UnityEngine.Random.Range(minX, maxX);
                SpawnPos.x = randomXPos;
            }
        }
        //if its far enough.
        if (randomXPos <= (stick.transform.localPosition.x - 5f) || randomXPos >= (stick.transform.localPosition.x + 5f))
        {
            break;
        }
    }
}
#

and this is my code

#

just added that debug.log and it realized its messed up...

#

So first stick was placed at 10
other one was generated at -22 but changed to 36

verbal dome
#

Also this while loop will be infinite if it fails to regenerate when your inventory is full -> unity freezes

lofty lintel
#

yeah I understand that

#

I'll have cap on how much stick u can take

#

and I'll lower the distance too so it don't looks weird either

verbal dome
#

I also feel like the || should be && instead

lofty lintel
#

I think...

#

it should be something like

#

or yeah-

#

wait...

verbal dome
#

Please hit enter only when you have an actual message to send

lofty lintel
#

Im sorry im kind of used to text like this.

lofty lintel
rocky canyon
#

seems overly complex..

            foreach (Vector3 pos in cachedPositions)
            {
                if ((randomPos - pos).sqrMagnitude < squaredDistanceThreshold)
                {
                    tooCloseToOtherSticks = true;
                    break;
                }
            }``` my example uses sqr distance threshold and just loops thru checking
#

instead of weird if/ or/ and/ conditionals

#

squareDistanceThrshold being float squaredDistanceThreshold = totalDistance * totalDistance;

#

totalDistance = the min distance i set to others

lofty lintel
#

ok I'll try to implement that code but only to be working with X axis

rocky canyon
#

10x10x10 = 1000 prefabs.. (got em all) ๐Ÿ˜ˆ

swift elbow
# rocky canyon

How did you make this so smooth and have it not use up a billion percent of your cpu and ram?

#

I've tried a custom pooling system before and it went so poorly...

lofty lintel
#

i mean like It erros for me

#

does it need specific library?

#

oh no wait

#

in ur case its vector3

rocky canyon
lofty lintel
#

yeah...

rocky canyon
#

its the squared length of a vector

#

(it just cuts down on processing power to figure up distances)

lofty lintel
rocky canyon
#

hmm yea, it doesnt need any special using statement..

#

im only using Collections.Generic for the lists i use

lofty lintel
# lofty lintel

it doesn't work for me because I do float x instead of Vector3 x

#

because well CachedXpos only takes X positions and I only want to make distance between X axis

rocky canyon
#

oh its b/c it returns a float..

lofty lintel
#

yep

#

That's what Im saying

rocky canyon
#

it should still work tho..

    bool IsPositionValid(Vector2 position)
    {
        float squaredDistanceThreshold = minDistance * minDistance;

        foreach (Vector2 existingPos in positions)
        {
            if ((position - existingPos).sqrMagnitude < squaredDistanceThreshold)
            {
                return false; // Position is too close to an existing one
            }
        }
        
        return true; // Position is valid```
lofty lintel
#

CachedXpos is List of floats

#

not Vector2s

rocky canyon
#

ahh gotcha

polar acorn
# lofty lintel

Couldn't you loop over the list of floats and compare position.x to it instead

lofty lintel
# polar acorn Couldn't you loop over the list of floats and compare `position.x` to it instead

            foreach (var stick in StickUIs)
            {
                //checking if position is compatebale with other sticks.
                while (randomXPos >= (stick.transform.localPosition.x - 5f) && randomXPos <= (stick.transform.localPosition.x + 5f))
                {
                    //if not change position
                    randomXPos = UnityEngine.Random.Range(minX, maxX);
                    SpawnPos.x = randomXPos;
                    foreach (var x in CachedXPos)
                    {
                        //check if its alright with any other alreadySpawnedStick x positions
                        if (randomXPos >= (x - 5f) && randomXPos <= (x + 5f))
                        {
                            Debug.Log($"{randomXPos} is inside the range |{randomXPos} >= {x - 5f} or {randomXPos} <= {x + 5f}|");
                            randomXPos = UnityEngine.Random.Range(minX, maxX);
                            SpawnPos.x = randomXPos;
                        }
                    }
                    //if its far enough.
                    if (randomXPos <= (stick.transform.localPosition.x - 5f) || randomXPos >= (stick.transform.localPosition.x + 5f))
                    {
                        break;
                    }
                }
            }```
#

This is what I did before

verbal dome
#

You still had || in the bottom if statement

lofty lintel
#

oh

#

wait

verbal dome
#

You want to check if it is far enough on the left side AND on the right side

lofty lintel
#

yeah

verbal dome
#

Wait it might be okay, lemme thin

lofty lintel
#

because logically when I do OR

#

it says either of one

#

so like if its less than 5 for example (its ok to be 6) right? and we don't want that

verbal dome
#

Alright nevermind, that if statement should be fine

#

Btw this logic tries to keep a distance of 10, not 5

lofty lintel
#

yeah I know

verbal dome
#

Because you are checking 5 on each side

lofty lintel
#

10

#

but 5 on each side

lofty lintel
verbal dome
#

I don't see the need for the inner foreach loop though. Isn't the while loop already doing that?

lofty lintel
#

So basically

#

when while breaks

verbal dome
#

Please write full sentences, let's not flood the channel

lofty lintel
#

it checks if current stick's distance is good enough for next stick

low wasp
#

Long time listener. 3rd time caller. I posted this a this a few days back. I have made some progress on other things. I am still stuck on how to disable movement on my players when the game is over. I had a few suggestions from before. I have not been able to figure them out. Would anyone be able try and point me in the correct direction again? I even tried to see if AI could help.

Shout out to Spawn Camp Games for trying last time.

https://hastebin.com/share/guruzapege.csharp

lofty lintel
#

With that foreach I try to check if current stick is far enough with other sticks' positions

verbal dome
rocky canyon
#

instead of worrying about input

#

just disable the thing tht moving the player in the first place

low wasp
#

I tried that and I could not get it to work either. It was weird as I got it to work for the car spawner. I even tried to copy the code and insert the correct bits. I just could not get it to work. Let me try that again.

lofty lintel
# verbal dome Okay, and what is the while loop for?

same thing but i think it only checked One stick, logically talking, if while checks one stick now and gets position of X at 5 and then after checking next stick turns Position at 4 because it was not valid and then checks next stick it would still allow to put it on 5

rocky canyon
true oriole
rocky canyon
#

and at the end. u can tell that almost works.. but my camera is still moving around..

#

so id have to disable my camera controller script as well

lofty lintel
#

also could u guys help me get those stones behind that brown UI?

#

They don't have Order in layers.

low wasp
polar acorn
# true oriole

Configure your !ide so you can see your lines be underlined in red when you've made a mistake

eternal falconBOT
rocky canyon
# low wasp So I tried coping the same command I used to disable the carspawner. It won't wo...
using UnityEngine;
using SPWN;

public class GameManager : Singleton<GameManager>
{

  public SpawnCampControllerLite controller; // needed to disable player movement
  public ControllerCamera cameraController; // needed to disable camera movement

  void Update() 
  {
    if(Input.GetKeyDown(KeyCode.X))
    {
      EndGame(); 
    }
  }

  // method to disable the things i need to stop player movement
  void EndGame() 
  {
    controller.enabled = false; // disable the character controller script
    cameraController.enabled = false; // disable the camera controller script
    Dbug.Stopped("Game has ended");
  }
}
lofty lintel
rocky canyon
lofty lintel
low wasp
rocky canyon
#

thats why i made my menu First

#

wheres the rest of the content?

#

iono lol ยฏ_(ใƒ„)_/ยฏ

peak cedar
rocky canyon
frosty hound
#

@willow shoal You're setting the bool an animation, not an animator type.

willow shoal
#

ok

rocky canyon
#

please ๐Ÿ“Œ note.. Find methods are not performant at all.. and shouldn't be called very often at all

#

but ending the game is a suitable use case imo

verbal dome
# lofty lintel I think I know what I can do... So Basically I can put like spawn and then like...

Alright so I don't usually spoonfeed but I'm bored and found this interesting. Something like this should work:cs bool foundAnyValid = false; float randomXPos = 0f; int maxTries = 1000; // Failsafe for (int i = 0; i < maxTries; i++) { randomXPos = UnityEngine.Random.Range(minX, maxX); bool valid = true; // The position is valid until proven otherwise foreach (var stick in StickUIs) { // Blocked? if (randomXPos >= (stick.transform.localPosition.x - halfSize) && randomXPos <= (stick.transform.localPosition.x + halfSize)) { valid = false; break; } } if (valid) { Debug.Log("Found valid: " + randomXPos); foundAnyValid = true; break; } } if (!foundAnyValid) Debug.LogError("Couldn't find a valid pos");

#

Could be some minor mistakes since I didn't test it with transforms but with a list of floats instead

rocky canyon
verbal dome
#

See how you don't need three nested loops but just two @lofty lintel

#

From the inner loop you break out as soon as any stick blocks the random position. Then the outer loop keeps trying new positions

#

If none of the sticks in the inner loop blocked it, we can break out of the outer loop since the position is valid

#

I even tested with a crappy GUI, those red boxes are the generated positions with halfSizeX * 2 as width

rocky canyon
#

the only thing i dislike about mine is the attempted counter that breaks out of the loop to keep it from being infinite.. (the only way i know how to do it is to have a limit)

true oriole
verbal dome
#

See the for loop with maxTries

#

Same thing

lofty lintel
polar acorn
rocky canyon
verbal dome
#

Definitely

rocky canyon
#

im just a bit ignorant on generative loops stuff like this

verbal dome
#

You see that a lot when doing these kind of "brute forcing" algorithms

rocky canyon
#

alrighty.. thats all i need to know ๐Ÿ‘ ๐Ÿ™‚

lofty lintel
verbal dome
lofty lintel
#

Ok now maybe im doing it wrong way

lofty lintel
#
bool foundAnyValid = false;
randomXPos = 0f;
int maxTries = 1000; // Failsafe
for (int i = 0; i < maxTries; i++)
{
    randomXPos = UnityEngine.Random.Range(minX, maxX);
    SpawnPos.x = randomXPos;//<------ Added this
    bool valid = true; // The position is valid until proven otherwise
    foreach (var stick in StickUIs)
    {
        // Blocked?
        if (randomXPos >= (stick.transform.localPosition.x - 5) && randomXPos <= (stick.transform.localPosition.x + 5))
        {
            valid = false;
            break;
        }
    }
    if (valid) { Debug.Log("Found valid: " + randomXPos); foundAnyValid = true; break; }
}
if (!foundAnyValid)
    Debug.LogError("Couldn't find a valid pos");```
#

Added that one line of code because Thats actually where I assign valid X position to spawnposition

verbal dome
#

You could add that line after the loops but it's fine

#

You might wanna try using anchoredPosition instead of localPosition though. I don't exactly remember how localpos behaves on UI/RectTransforms

lofty lintel
#

there is no such a property

rocky canyon
#

if its a sprite localPosition is fine.. if its a UI element (image) i think anchoredPosition is the better method

verbal dome
#

If it's even needed, that is

rocky canyon
#

theres no property for a gameobject/Transform ur correct..
but if they are UI images u should be using the RectTransforms

lofty lintel
rocky canyon
#

ya, i get that.. but when placing them.. its usuaslly better to use the RectTransform of the gameobject

lofty lintel
#

this is how I add them StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));

verbal dome
#

GetComponent<RectTransform>() instead of transform

lofty lintel
#
{
    valid = false;
    break;
}```
rocky canyon
#

ya, but u should probably just have RectTransforms as ur types in general

verbal dome
rocky canyon
polar acorn
lofty lintel
#

oh ok

rocky canyon
#

we get that alot where people put in what they think is good coordinates.. but b/c its a UI element they wont appear where people expect..

#

thats why they'll get suggested to use RectTransform component instead

lofty lintel
#

oh so thats common case

low wasp
rocky canyon
#

but like Osmal mentioned earlier.. it may not even be a problem for your use-case

#

just mentioned

rocky canyon
low wasp
rocky canyon
#

u could put a method in ur CharacterController script that calls this line ^

#

before its disabled the important part being before

low wasp
#

Right on

rocky canyon
#

stopVelocity is a vector3 ofc..

#

Vector3.zero

#

its odd that ur player keeps its momentum tho...

#

my CharacterController stops dead in its tracks.. even whether im grounded or not

lofty lintel
#

so I did this.

 {
     StickUI.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
 }```
rocky canyon
vestal isle
#

I'm facing a strange bug where a boolean is never changed for a single script and it all points to it being changed.
I even had used a Debug.Log and there it says the value is false, but in Update the value says true atwhatcost

lofty lintel
#

Prefab.

low wasp
rocky canyon
#

public RectTransform StickUIPrefab;

slender nymph
rocky canyon
#

right..?

polar acorn
rocky canyon
polar acorn
#

Show full !code

eternal falconBOT
vestal isle
lofty lintel
rocky canyon
#

thats because u probably have something before that Instantiate

polar acorn
rocky canyon
#

works fine here

polar acorn
rocky canyon
slender nymph
slender nymph
rocky canyon
#

change the expectation to RectTransform.

lofty lintel
#

Ok wait guys I'll send the whole code now

polar acorn
rocky canyon
lofty lintel
#

!code

eternal falconBOT
vestal isle
lofty lintel
slender nymph
# rocky canyon thank you

it also has an implicit cast to UnityEngine.Quaternion. but also fun fact about Mathematics.quaternion, it's Euler method expects radians instead of degrees for whatever reason

lofty lintel
vestal isle
#

It must be some kind of classic Unity bug

polar acorn
vestal isle
vestal isle
#

multiple tabs

rocky canyon
vestal isle
slender nymph
# vestal isle

you should also include the InstanceID when printing info, or at the very least add the context parameter so you can click and see which instance those logs come from

polar acorn
#

There's no log in there

rocky canyon
#

the amount of times i've thought the computer was lying to me

vestal isle
low wasp
rocky canyon
#

so thank urself ๐Ÿ’ช

lofty lintel
rain hull
#

https://paste.ofcode.org/APuXHwM36PjbMCYRyJR5ku I have this code I wrote to reset the characters position when it comes into contact with anything with a contactLayer but it wont work even though theres no issues with how the code it written, need some help

vestal isle
#

And now when updating the Unity version to 2022.3.48 it never changes the state to Playing atwhatcost

#

Okay, Unity ..

polar acorn
#

The code does exactly what you tell it to do

vestal isle
#

It is if the version matters

drowsy oriole
#

I want to call a function when a gameobject is Enabled/Disabled, How would I do this?

polar acorn
#

Chances are you have a race condition and it will change literally every time you restart the project

rocky canyon
#

100% of the time you've accidently coded it to lie to you

#

other than that.. it is what it is lol

slender nymph
polar acorn
#

because the order of functions like Start and Update are basically random

vestal isle
drowsy oriole
#

How would I use it in this sit.

public void ResetFur()
{
    MonkeMesh.material = FUR;
}

public void ChangeFurToFall()
{
    MonkeMesh.material = FallFur;
}
polar acorn
vestal isle
#

But however .. There is no way that this bug is order of execution since it subscribes to the event

#

Unless it magically unsubscribes

rocky canyon
#
void OnEnable()
{
  ResetFur();
}```
drowsy oriole
#

When GameObject FallCosmetic is active, MonkeMesh.Material = FallFur

polar acorn
rocky canyon
#

well then put the other method in there

#

lol

rocky canyon
lofty lintel
#

Ok i'll go now, i'll fix this later.

vestal isle
#

It detects paused as false for EVERYTHING but a single darn script and I have no special code there. That's what bothers me.

lofty lintel
#

ty guys!

rocky canyon
#

not a solution for all situations.. i just wanted to mention it

charred cedar
#

hey quick question but does anyone know how to type script in unity im new to it

vestal isle
#

OnResume is called and I had a Debug.Log tell me that the value is FALSE.

However in Update the value says that it's true

#

As if its passed by value

polar acorn
slender nymph
charred cedar
polar acorn
eternal falconBOT
#

:teacher: Unity Learn โ†—

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

charred cedar
polar acorn
# vestal isle

I don't see the GameStateChanged message in here, and that "Paused value True" doesn't have the instance ID

vestal isle
#

Hold on, let me record.

polar acorn
#

So it doesn't show anything

#

All it shows is something has its paused value set

#

but that might not be this thing

polar acorn
slender nymph
charred cedar
polar acorn
charred cedar
slender nymph
vestal isle
polar acorn
#

That one's kind of important

vestal isle
charred cedar
#

is the um beginner scripting thing?

vestal isle
#

I don't want to log every single object that inherits the script, but only the specific script I'm looking for

polar acorn
#

You could also override that function in this script and check it there

slender nymph
#

print the name and instance ID in that log you have inside of Update too. it's rather suspicious that the logs show you have a positive instance id. it's typically negative for instances of a prefab (or just non-assets)

vestal isle
#

This is literally the debug.log that you posted

#

top and bottom

polar acorn
#

Where's the one in GameStateChanged

vestal isle
#

Oh, you mean that.

polar acorn
#

I very specifically included two logs to use

vestal isle
#

I see, my apologies

polar acorn
#

so that you could compare the InstanceIDs

vestal isle
#

They both match

polar acorn
#

Also, just to be sure, your log in update is before the return, right?

vestal isle
#

yes

#

at the top of the update

polar acorn
#

Okay, just making sure

vestal isle
#

let me serialize the property

#

to check in the inspector at runtime too

polar acorn
#

Add these functions to your player script. These will run instead of the normal OnPause/OnResume of the parent class. Make sure it's getting both messages.

protected override void OnPause()
{
  IsPaused = true;
  Debug.Log($"{gameObject.name} [{this.GetInstanceID()}] is pausing");
}
    
protected override void OnResume()
{
  IsPaused = false;
  Debug.Log($"{gameObject.name} [{this.GetInstanceID()}] is resuming");
}
rain hull
polar acorn
# vestal isle

Are any of these other ones child classes of PausableMonoBehaviour

vestal isle
vestal isle
polar acorn
#

The one in your bin was Player

slender nymph
rocky canyon
vestal isle
#

Check the script I sent above

polar acorn
#

Oh, I was still looking at the multi-tabbed bin you sent first

vestal isle
#

This might be the strangest bug I have ever had in Unity

#

or it's just me .. But impossible .. heh. ๐Ÿ˜“

polar acorn
#

I'm pretty sure what's happening here is that there's multiple IsPaused variables due to inheritance shenanigans. There's PausableMonoBehaviour.IsPaused and PlayerShooting.IsPaused and it's setting the first one inside of PausableMonoBehaviour but using the second

rain hull
polar acorn
#

I'm just trying to figure out why and how we can check

slender nymph
vestal isle
#

Maybe I can try with an interface? ๐Ÿคทโ€โ™‚๏ธ

#

or abstract to force the inheritor to declare it

polar acorn
vestal isle
#

also happening on Unity "6000", so it's probably strange Unity behavior

polar acorn
#

This is strange C# behavior. Inheritance does some weird things sometimes if you don't do it exactly right

#

I don't see anything awry but I also have run into this problem myself before so I am prone to miss it

rain hull
#

Ill leave it next time, again thanks for the help either way

slender nymph
#

yeah for future reference, do not modify the code when sharing it. that includes leaving your debug statements in so we can actually see exactly what you are doing.

polar acorn
vestal isle
#

Yeah, found it as well

polar acorn
#

Did you perhaps subscribe to the wrong event somewhere

vestal isle
#

lets try with caller attribute

slender nymph
#

can you not just look at the stack trace?

vestal isle
#

That is true

polar acorn
#

Would that show what called the function that invoked the event? Or would it just go cold at the event?

slender nymph
#

should show where the event was invoked

polar acorn
#

Yeah, check that

vestal isle
#

uhh ...

#

Input ????

#

Oh, yeah. Right.

slender nymph
#

looks like OnPause is subscribed directly to an input action

vestal isle
#

Oh my god.

#

Maybe ???

#

Nope, no interactions. But lets see.

polar acorn
vestal isle
#

Oh my god, I know what it is

#

the input system was calling OnPause function obviously via SendMessage

#

๐Ÿคฆโ€โ™‚๏ธ

polar acorn
#

You have a button named "Pause" dontcha

#

And a PlayerInput component that sends messages

vestal isle
#

That's so stupid and so obvious

slender nymph
#

this is why i generate the c# class and manually subscribe to events. can't have SendMessage invoking private/protected methods that way

vestal isle
#

Yeah, that's what I used to do. But I grew tired of it, too much init code needed for it.

#

Thanks everyone who helped, respect y'all. ๐Ÿฉต

polar acorn
#

Remember - it's always the human's fault. We're very good at making complicated problems

cosmic dagger
#

eww, SendMessage . . .

slender nymph
#

yeah i prefer the manual setup over the reflection lol

vestal isle
#

Confirmed it works now.

I should for sure use manual way next time. This was a pain

lost anvil
#

why is this code unreachable?

` public void RemoveItem(Item item)
{
for (int i = 0; i < slotList.Count; i++)
{
int slotIndex = itemList.IndexOf(item);

        Destroy(slotList[slotIndex].transform.GetChild(0).gameObject);
        itemList.Remove(item);
        break;
    }
}`
slender nymph
#
  1. !code
  2. it generally helps to point out which line the warning/error is on
  3. you break on the first iteration so that being a loop is completely pointless
eternal falconBOT
lost anvil
#

this one mate
for (int i = 0; i < slotList.Count; i++)

eternal needle
#

that warning should be on the i++; part specifically, which happens after the for loop iteration. and read boxfriend's 3rd point

slender nymph
#

please read the entire message

lost anvil
#

๐Ÿ‘

polar acorn
lost anvil
#

its fine i just got rid of it its 1am give me a break๐Ÿ˜‚

peak cedar
#

So I have a object with a RigidBody and Box Collider that has a chance of falling through a Terrain, and it's only 2 meters off the ground. There something to avoid that?

verbal dome
#

Likely you are moving the rigidbody incorrectly (with transform instead of rigidbody) or it's moving too fast and you don't have continuous collision enabled on the RB

peak cedar
#

Oh the object is just following physics, though I did forget to add I'm randomly rotating it and applying velocity on spawn (basically flinging it a little). But if I need continuous collision then that'll be what I need to do then.

teal viper
peak cedar
# teal viper If you're rotating the transform directly, it could cause issues as well. Make s...

Yeah I was directly. Seems fine during a Start for how this object is placed in particular, but updated it regardless.

void Start() {
  Rigidbody rigidbody = GetComponent<Rigidbody>();
  if (rigidbody != null) {
    if (fling) {
      rigidbody.angularVelocity = RandomVelocity(flingRotation);
      rigidbody.velocity = RandomVelocity(flingVelocity);
    }
    if (randomAngle) {
      rigidbody.MoveRotation(UnityEngine.Random.rotation);
    }
  }
}
hardy geode
#

can someone tell me how to fix this cuz I don't understand it

rich adder
wintry quarry
hardy geode
#

let me check

hardy geode
verbal dome
#

Did you try searching t:ailocationselectorscript in the scene?

hardy geode
#

there is only one

ivory bobcat
#

Click the clear button

verbal dome
#

Im not even sure if a serialized array/list can be null ๐Ÿค”

ivory bobcat
#

Show the contents of the script

hardy geode
#

ok

verbal dome
#

Oof, is this decompiled

hardy geode
#

yea :C

#

I opened a new decompile that is the same one

#

at it looked fine

#

idk what went wrong

teal viper
hardy geode
#

alright then

cosmic dagger
upper thistle
#

Anyone have a suggestion for the best way to go about starting a single coroutine do I just use a boolean to make sure it doesn't spam it? Or is there some kind of special unity library function for this

cosmic dagger
upper thistle
north kiln
#

Note that you still have to set it to null at the end if the coroutine completes

upper thistle
#

Appreciate that though

#

didn't know about the null stuff

#

So it's kind of a self boolean

cosmic dagger
#

yes, setting the coroutine to null at the end of the coroutine method is important . . .

cosmic dagger
upper thistle
#

tryna wiggle my way in with the random asset stuff while I focus on discovering new code lol

cosmic dagger
nocturne kayak
#

Ladies and Gentlemen

#

it works

#

i haven't had a sigh this sweet in weeks

#

now next steps are:

#

1.Lerping\SmoothDamping this thing

#

2.Stopping this at collision

upper thistle
#
    IEnumerator Heal()
    {
        if (animator.GetBool("IsDowned"))
        {
            Debug.Log("Healed!");
            currentHealth += maxHealth / 10;
            healthBar.SetHealth(currentHealth);
        }
        yield return null;
    }```

```CSharp
        if (currentHealth <= 0 || animator.GetBool("IsDowned"))
        {
            if (currentHealth < 0)
            {
                currentHealth = 0;
            }

            if (currentHealth >= maxHealth)
            {
                currentHealth = maxHealth;
                animator.SetBool("IsDowned", false);
            }
            healthBar.SetHealth(currentHealth);
            animator.SetBool("IsRunning", false);
            animator.SetBool("IsJumping", false);
            animator.SetBool("IsDowned", true);
            if (Time.time >= nextTime)
            {
                StartCoroutine(Heal());
                nextTime += interval;
            }
        }
    }```

It works as intended except it fires off anywhere from 5-20 calls right when the healing starts. I assume I setup the coroutine or timer improperly, but require some guidance if possible please.
https://gyazo.com/4de55036db59ecf297e0cc9351044e44
#
    private int interval = 1;
    private float nextTime = 0;
``` ^ is used for my timers
deft grail
eternal falconBOT
deft grail
upper thistle
#

Oh

#

Ty

#

the timer normally works as intended minus the initial misfire in the first second, but I'm assuming it's that or how I null the coroutine

fickle halo
#

why can't I name a function โˆš while I can name a function ฮ”

deft grail
fickle halo
swift elbow
#

not sure which in c#

fickle halo
#

think its just that they dont support arbitrary symbols

swift elbow
#

yeah or its not unicode

north kiln
thorny basalt
north kiln
#

Anyway, that's the complete answer to your troll question

cosmic dagger
#

symbols make the code less readable . . .

north kiln
#

They are well aware of that

cosmic dagger
#

that should be the least of your worries . . .

fickle halo
thorny basalt
#

They also break naming conventions. You canโ€™t use special characters in code other that @ symbols

fickle halo
#

do you think Vector.add(Vector) is more readable than Vector + Vector @cosmic dagger

fickle halo
north kiln
#

Because it's obvious that it's an unreasonable thing to type

fickle halo
fickle halo
#

not a worry at all

#

its in fact easier to type than Time.deltaTime, lol

thorny basalt
#

This is illegal

north kiln
#

Only if you didn't also make a snippet for that

fickle halo
#

its a good thing we can do that.

#

its workspace wide so all members of the team have it automatic on their machines btw

#

zero config

north kiln
#

Do those snippet files work on other IDEs?

fickle halo
cosmic dagger
fickle halo
#

that is a very small criticism that is outweighed by the readability benefits in our opinion

fickle halo
#

you guys are trying to be haters, lol

north kiln
#

Well colour me surpised that it's not a troll, but yeah, it's not gonna work for non-letter characters unless they're also in the spec I linked

swift elbow
cosmic dagger
fickle halo
#

not everyone will know what the delta symbol is . . .
it would take them 2 seconds to learn the symbol and then have it dedicated to memory forever

#

our team is 4 people also

thorny basalt
fickle halo
#

code looking unfamiliar doesn't mean its not more readable, once you familiarize yuorself with it

#

and then you hover your mouse over it, and you see the intellisnse "alias for Mathf.sqrt()"

thorny basalt
fickle halo
cosmic dagger
#

no hating here, we're just giving a general view of its use. a snippet could easily be made that auto-typed Time.deltaTime instead of creating a snippet that gave a delta symbol which pointed to Time.deltaTime, just seems like an extra step that's unnecessary . . .

fickle halo
cosmic dagger
fickle halo
#

Time.delta would have been acceptable I think. But Time.deltaTime... tf were they thinking

cosmic dagger
north kiln
#

I like stupid shit like making the division operator for strings act as path concatenation, and other silly things like that, but I personally think that outside of it being a self-contained library "neat" isn't much of a value add. But whatever, nobody is stopping you and if your team likes it that's great

fickle halo
cosmic dagger
#

also, i'm curious, how do you write fixedDeltaTime?

north kiln
#

there's almost never a reason to use fixedDeltaTime anyway ๐Ÿ˜„ it's so rare to need it

fickle halo
cosmic dagger
north kiln
#

:fdt -> fixedฮ”t

fickle halo
#

but if turn on my symbol mode...

#

its all on one line now

cosmic dagger
cosmic dagger
fickle halo
north kiln
#

what's going on with the Vector3 replacement

fickle halo
#

i have a visual substitution extension setup

#

its purely visual

cosmic dagger
#

bro, even the Vector? omg . . . ๐Ÿ˜ฒ

north kiln
#

lol if you're gonna go all out... give me a sec

fickle halo
#

you'll notice ive also hidden semi colons and curly braces

#

lol

thorny basalt
fickle halo
#

it is important that code reads the same for everyone

#

so we have a team rule not to use word wrap

#

and keep things fitting on 1 line

north kiln
thorny basalt
fickle halo
nocturne kayak
#

Quick question, but is there a way to check if a collider's, well, colliding

#

even if there's no rigidbody?

north kiln
#

the ligature list scrolls lol

fickle halo
#

usually, creating an entire variable, then using it an equation, reads less fluidly than just having 1 short equation

#

your brain interprets it as two steps

cosmic dagger
#

are you limited to under 90 characters per line?

fickle halo
#

we are self-limiting ourselves to "this code must fit on a 13-inch macbook at default vscode settings"

#

whatever line count htat is

cosmic dagger
fickle halo
thorny basalt
fickle halo
#

its just sort of jagged now

#

better I guess

#

but still

#

not even close to how readable and sleek this is

#

and now that im using a visual substitution extension, you can just type Time.deltaTime

#

the real text is that.

north kiln
cosmic dagger
fickle halo
#

logic symbol for and

north kiln
#

๐Ÿค•

nocturne kayak
nocturne kayak
#

thx

cosmic dagger
# fickle halo

yea, you lost me with the last two symbols. this looks like MonoBehaviour is magnetized or pointing to Jump . . .

fickle halo
#

@cosmic dagger

north kiln
#

meanwhile I'm over here making my variables as verbose as possible

nocturne kayak
fickle halo
#

numbers.All

nocturne kayak
#

my object IS a kinematic rigidbody trigger

#
    void OnCollisionEnter(Collision collision)
    {
        Debug.Log("You're colliding yo");
    }
}
#

and i added this snippet of code in there

fickle halo
nocturne kayak
#

but it's still not printing that debug

north kiln
cosmic dagger
# fickle halo

yeah, this is foreign to me. that looks like a protractor for an angle. i would have thought it meant angle or the 'A' was upside down. this is already too many symbols for me . . .

fickle halo
nocturne kayak
#

Where can i read more into that?

fickle halo
#

oh responding to wrong person

cosmic dagger
#

or is it the compass, not the protractor . . . i think . . .

north kiln
#

it's a funnel

fickle halo
#

upside down A

#

for ALL

north kiln
#

I'm glad you enjoy this level of unreadability lol

fickle halo
#

it is a level of huge readability for people who are familiar with the symbols lol

north kiln
#

I'm very glad I have programming so I don't have to learn symbology to do maths

fickle halo
#

all programming comes from maths /shrug

#

i like the idea of gatekeeping my codebase with the formal symbols of everything a bit tbh

#

"dont touch this code unless you are a wizard"

north kiln
#

If I learnt programming before being taught maths I would have learnt so much more maths, but they really had to just make everything theoretical with an expanding set of unreadable symbols

fickle halo
#

yeah

swift elbow
north kiln
#

That's good for you mate

swift elbow
#

im not saying that to brag, im saying that to show how easy it is if you try

cosmic dagger
cosmic dagger
north kiln
#

I know what the symbols mean, it's still a self-centered and unapproachable style. Doesn't mean they shouldn't do it, but if this was how C# was written more broadly it would be much harder to learn.

cosmic dagger
swift elbow
cosmic dagger
#

anyone who knows a skillset can say, "it's easy if you try," but each skill has a different learning curve and barrier of entry for the general populace. my friend, she's a polyglot, and says the same thing, "learning any language is easy, if you just try . . ."

cosmic dagger
swift elbow
swift elbow
north kiln
#

unexpected density decreases readability because of unfamiliarity with symbols vs words, and that'd probably be where I fall down. It'd be like reading shaders where they've named everything single letters. I'd have to come along and expand them if I wanted to work with it

#

maybe it'd be fine for myself to use that much, but I'd hate to drag a team along

#

especially if I had to make any new hires haha

cosmic dagger
#

complexity is based on an individual's perception of said topic. i've definitely seen people struggle with a simple instruction or topic which they saw as complex. i've even done so myself . . .

swift elbow
north kiln
#

It's not arbitrary when you have standards and have been using a language with them for 10 years

swift elbow
#

similar to that one Einstein quote

#

if you cant explain something to a 5 yr old, then you dont really understand it

cosmic dagger
swift elbow
#

i never said it had to be "one-size-fits-all"

cosmic dagger
#

learning how to program felt easy for me; it was like reading a book. i do feel anyone can learn how to program (of course at different levels). the hard part is the logic behind it all. it's the . . . how is A going to sync with B. how do we fit C and D into B. does D need A? it's like putting a puzzle together with pieces that you (still need to) build . . .

swift elbow
#

its simply a matter of perspective

cosmic dagger
#

yep. for some it's 2D, 3D, or 4D . . . ๐Ÿ˜†

fickle halo
#

to the programmers who already know these symbols, it is faster on their eyes to read the symbol version than the verbose Time.deltaTime version

#

so its a tradeoff of who we are priotizing. I want faster readability for the pros on my team, even if it makes my code a bit alien and scary looking to the less experienced/knowledgeable developers

#

it is elitist for sure. But we think thats a good thing

near jewel
#

so uh idk if this would be ui help or coding help cause i have no idea what's going on. i have a textmeshpro menu that lerps positions when the button is selected and the code seems to be working fine, but when i press the button it goes back to its original position? it works fine if the buttons are set to color tint or animation instead of sprite swap, but i need it to be sprite swap. i'm not entirely sure what i'm doing wrong?

#

the buttons are on a grid layout group with a content fitter which i suspect might be fucking with it but i need those too

#

ok as i wrote that and realized it might have been the grid layout group i checked it and it was and idk what to do about it

deft lynx
#

sorry guys, where do i ask for help, I'm having issues with my project

eternal falconBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

languid spire
near jewel
#

thank you

quick kelp
#

hello I've been trying to code this solar box puzzle
i got to rotation to working in a separate script but i can seem to get the solve function to fire off even tho all the transforms are at the correct rotation angles

using System.Collections.Generic;
using UnityEngine;

public class SolarBox : MonoBehaviour // PascalCase is Conventional for class names in C#
{
    [SerializeField] private List<Transform> _rings;
    
    [SerializeField] private List<float> _correctAngles; 
    
    
    private void Update()
    {
        bool isFail = false;
        foreach (var ring in _rings)
        {
            float currentAngle = Mathf.Round(ring.rotation.eulerAngles.z * 2f) / 2f;
            
             //Debug.Log($"Current Angle: {currentAngle}");
            if (!_correctAngles.Contains(currentAngle))
            {
                isFail = true;
                //Debug.Log("Angle is incorrect.");
                break;
            }
        }
        if (!isFail)
        {
            OnSolved();
        }
    }

    private void OnSolved()
    {
           Debug.Log("PUZZLE IS SOLVED!!!");
    }
}```
languid spire
quick kelp
#

any advice on both points

languid spire
#

first one is difficult, you would need to maintain your own rotation vectors for each ring.
second one, dont use .Contains, make a for loop and compare the difference between the numbers

eternal needle
# quick kelp hello I've been trying to code this solar box puzzle i got to rotation to workin...

even for that .Contains point, it seems wrong to use this. this seems like it doesnt matter if the rings are in a specific rotation, just that any ring has a rotation from this list. is this intended?
With 2 rings and the goal being ring A = 90 degrees, ring B being 45 degrees, the solution could be or (A=90 and B=90) or (A=45 and B=45)
You should instead check the same index of your _rings and _correctAngles. Meaning rings[0] checks the angle at _correctAngles[0]

dry geyser
#

Hello, im relatively new to unity and im following a multiplayer fps game tutorial and i keep getting this same issue no matter what tutorial i follow (im using Photon Pun2) the code thats causing the error is this: Anyone know how to fix it?

#

it prints creating controller then it errors

burnt vapor
#

Validate your Photon events or something, apparently

dry geyser
burnt vapor
#

I assume the tuturial has a git repo you can compare with

dry geyser
#

Ok, ty

snow warren
#

i have a question

#

i am doing something like this

#

if (!UAEFileRoot.Find("AssetsFiles").Find("Managed"))

#

this is an if statement

#

now inside the if statement i am checking if the gameobject has a child or not

#

do i have to do it like this

#

if (UAEFileRoot.Find("AssetsFiles").Find("Managed") == null)

#

or this can also work

#

if (!UAEFileRoot.Find("AssetsFiles").Find("Managed"))

#

helps are appreciated

devout flume
#

Normally it works

eternal needle
devout flume
#

Also, I'm unsure on whether or not UAEFileRoot.Find("AssetsFiles") can return null, if you use a method that may return a null reference, and you still want to run code out of it, you may do

UAEFileRoot.Find()?.Find()
devout flume
snow warren
eternal needle
#

null conditional (the ?.) shouldnt be used on unity objects

devout flume
#

So you may not ALWAYS find this specific type

snow warren
#

then it will return null

#

no matter what

devout flume
eternal needle
#

so if you use null conditional or null coalescing then you can get it to return true, when the object was already destroyed. unity will return false if its destroyed

devout flume
#

Oki good to know, thanks

eternal needle
#

im not sure it actually matters in their case, because the only issue i know is if the object existed at one point and is destroyed. but just better practice to not do it rather than be unsure of if you can

night valve
#

really quick sanity check if this makes sense:

using UnityEngine;

public class DontDestroyOnLoadMono : MonoBehaviour
{
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}

any votes against?

teal viper
night valve
#

reason why i ask - thought there is some built-in tag or something to mark objects without need of attaching such script, so maybe that absence has a reason

eternal needle
night valve
#

of course, matter of preference, but having it separate is more mainainable for me

teal viper
eternal needle
#

๐Ÿคทโ€โ™‚๏ธ it's exactly as maintainable as if you didnt separate this. Imo this is just bloat

night valve
#

it depends on an object, i came with that solution for GlobalVolume for example, that has no custom scripts other than that

teal viper
#

Or are you gonna put component on every single object you want to be DDOL?

night valve
#

parenting is good idea actually. About other objects - that would depend if their other scripts should worry about this or not

drowsy oriole
#

Hold up wait I want to look at unity learn !learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

formal sable
#

Hey... Can you help me, please?

verbal dome
#

Does your rigidbody have extrapolation enabled?

#

If not, how are you moving it? Charactercontroller or rigidbody? Show code

formal sable
verbal dome
#

Don't enable it, was just checking

#

You might wanna enable interpolation though

verbal dome
#

Yeah

#

Camera code might be relevant too

formal sable
verbal dome
#

Use rigidbody.velocity or addforce instead

#

As a bonus, you might want to use an early return instead of nested if-statements: if(isFrozen) return;, same with the pause check

#

Helps with readability IMO

#

Get rid of the transform.rotation too, use rigidbody.MoveRotation(Quaternion.Euler(x,y,z)) instead

formal sable
#

What about code of Camera Looking?

turbid robin
#

i think there are some error in my code but why dont the ide higlight them?

slender nymph
#

!ide

eternal falconBOT
verbal dome
#

Camera code looks ok

formal sable
nocturne kayak
#

Since @verbal dome is around

#

No problems for you today

#

it just worksโ„ข

#

Thanks for you help, man

verbal dome
#

Nice!

verbal dome
formal sable
verbal dome
#

Is the current issue exactly the same as in the video you posted?

#

Also might wanna use rigidbody.rotation.eulerAngles instead of player.transform.eulerAngles here

verbal dome
#

Nah just the part where you apply the rotation

#

And maybe the velocity too but I think it's fine in Update

#

Generally speaking you should do physics stuff in FixedUpdate

tender stag
#

does transform.GetComponentInChildren also return it if its on the transform?

slender nymph
#

yes

tender stag
#

alright

hexed terrace
#

you don't even need the transform. .. you can just do GetComponentInChildren<T>()

tender stag
#

if its on the object that the script is on then yeah ik

tender stag
hexed terrace
#

righto

tender stag
#

whats this about then

verbal dome
#

It probably used to be a monobehaviour and you added it as a component, then removed monobehaviour

tender stag
#

right i know why

#

i copied this system from my old game

#

the class is called WorkStation

#

but the script is called WorkBench

verbal dome
#

Filename should match the class name unless you are using newer unity versions

tender stag
#

yeah i know

slender nymph
#

more specifically, it must match the name of the MonoBehaviour contained in it. it has literally no effect whatsoever on plain classes

#

and even in the latest versions, if you have multiple types in the file it should match the name of the MB in it (still no multiple MBs per file, but that should be avoided anyway)

formal sable
nocturne kayak
verbal dome
#

I forgot which way around it is

verbal dome
turbid robin
#

@rich adder (to continue the discussion)

formal sable
# verbal dome Broken in what way?

well, for example, if I press D, the character goes to the right, but if I turn the camera to the left, then when I press D, he goes back... And the jump broke, he doesn't jump at all now

rich adder
turbid robin
#

each time in the for i am creating the block, setting the color as black and i want now to move the block

verbal dome
rich adder
# turbid robin its 2d

okay if camera is ortho then no need to worry about the nearClipPlane but the process is the same. Screen / View to World will translate your screenpose (0,0) to world equivalent

tender stag
#

how can i check where i already used this

#

cause i have to many scripts

rich adder
#

forgot what the option in VSC is

formal sable
verbal dome
#

Sure

rich adder
#

find all References

#

right there

#

it should tell you each file it was used in

tender stag
verbal dome
#

yAngle could be your rigidbody's y angle or your camera's y angle

turbid robin
rich adder
# tender stag

oh thats weird..maybe its counting that one as its own thing?
You could also search by name/keyword in all files in solution

verbal dome
#

(The reason you didn't have to do this before is because you were using Transform.Translate which works in local space by default)

formal sable
verbal dome
rich adder
tender stag
#

i was coming up with a system which i scrapped

rich adder
#

Oh would think interaction type to be an enum
look interesting as SO though

verbal dome
#

And for the jumping, you need to disable the walking rb.velocity when you are not grounded (falling or jumping), otherwise it will override your jump velocity

tender stag
#

specific ones

rich adder
verbal dome
turbid robin
rich adder
#

thats typically how you spawn stuff

sand snow
#

Can someone please explain to me why Input.GetKeyDown is detecting the desired button sometimes, instead of everytime

#

i can provide the code

rich adder
rich adder
sand snow
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;
    public float jumpForce;

    Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void FixedUpdate()
    {
        rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);

        if (Input.GetKeyDown(KeyCode.Space)) 
        {
            rb.AddForce(new Vector2(rb.velocity.x, 1 * jumpForce));
        }
    }
}
formal sable
steep rose
#

i told you this before (i believe)

rich adder
#

FixedUpdate runs at a specific interval

sand snow
#

ohhhh okay thank you for explaining

steep rose
#

and FixedUpdate is framerate independant and it runs on the physics step so you wouldnt get it every time

formal sable
rich adder
# turbid robin oh ok

yeah usually its something like
Vector3 position = startPosition + new Vector3(x * (squareSize + gap), y * (squareSize + gap), 0);
etc

sand snow
# steep rose get it out from fixedupdate

i thought you were telling me to take it out yesterday because i was using postion which is not physics based, i didnt realise you were telling me to take it out because of that

verbal dome
#

You posted the whole script, yes you need it

steep rose
#

here give me a minute

formal sable
verbal dome
#

Btw you can also just enable interpolation from the rigidbody inspector but setting it from code is ok too

formal sable
sand snow
tender stag
tender stag
#

why is the bool false?

#

i set the default to true

steep rose
sand snow
steep rose
tulip nimbus
#

Now im very confused as to why this doesnt work.

When a Ball (Prefab with the shown Code attached) touches the Player with the "Player" tag its supposed to Destroy itself. What did i do wrong?

sand snow
#

I just want to understand why its wrong, so I actually learn

steep rose
#

im having a brain fart rn

sand snow
steep rose
sand snow
#

bruhhhhh why is coding so hard ๐Ÿ˜ญ

steep rose
#

its not im just having a brain fart to help rn, so give me a minute ๐Ÿ˜