#💻┃code-beginner

1 messages · Page 22 of 1

rich adder
#

yes

#

whichever you have

fickle knoll
#

i have visuial studio

pearl coyote
#

If in the first place you dont have this checked it means you didnt even follow the tutorial 💀

fickle knoll
#

ive downloaded that like 5 times alrady

#

alrady

pearl coyote
#

It is checked?

polar acorn
pearl coyote
#

Also cheeck on this

fickle knoll
#

yes i also have that

slender nymph
#

screenshot your entire IDE window with the solution explorer visible

rich adder
#

chances are solution needs rebuild

pearl coyote
#

By the way does someone know whats happening for me with the material? 💀

fickle knoll
pearl coyote
pearl coyote
#

Looks like its not loaded correctly

rich adder
#

yeah the solution isn't open

slender nymph
# fickle knoll

close visual studio, go into unity and regenerate project files. after that double click a script inside unity to open it in visual studio

rich adder
#

also if there is a compile error all this config won't do much

fickle knoll
#

how do i regenerate project files (sorry for being dumb)

rich adder
#

in external tools

#

edt > preferences

slender nymph
polar acorn
fickle knoll
#

-_-

rich adder
# fickle knoll -_-

You'll need to do lots of reading thru documentations if you plan on making a game, better get used to it

fickle knoll
#

where tf is regenerate project files

rich adder
#

didnt even select Vs 😔

#

so much for "did it like 5 times"

fickle knoll
#

shhhh...

low chasm
#

☠️

summer stump
fickle knoll
#

ty

slender nymph
rich adder
#

it literally has screenshots, so its not even reading issue

#

just laziness lol

slender nymph
#

doesn't follow the instructions
tHe InSTruCtIoNs DoN't WoRK

gaunt swan
#

No NeoVim, very disappointing... atwhatcost

fickle knoll
#

now Vs looks diffent

rich adder
#

how would you use a debugger with neovim

fickle knoll
#

i think its right

gaunt swan
dry tendon
#

how can i make true this var

#

with this other code?

rich adder
dry tendon
rich adder
#

access the member, change it

coarse moss
#

So I'm building some logic to have a crop growing section of my game. I have two tile maps, the base and the crop tilemap. My crop tilemap is at order layer 1 while my base is 0. Why is my mouse position reading the base layer even if I draw on the crop layer? e.g. if base has tile 1 and crop has tile 2, I log the tile that is being clicked and it says tile 1 is the one being clicked no matter what. How do I get my mouseposition to read the highest layer and not only the base layer?

dry tendon
slender nymph
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

fickle knoll
#

does it look right now?

lofty sequoia
#

is it bad to be setting an image's color for a transition this way?

_image.color = new Color(_image.color.r, _image.color.g, _image.color.b, alpha);```
lofty sequoia
#

all I want to do is change the alpha, but it's readonly

slender nymph
rich adder
polar acorn
fickle knoll
#

.....

low chasm
#

bro is being ganged on 💀

fickle knoll
#

but it works now right?

slender nymph
#

yes, it is now configured correctly

rich adder
#

and u don't get roasted

fickle knoll
#

moral of the story: i suck at following guides

dry tendon
slender nymph
rich adder
low chasm
fickle knoll
#

im blind

#

👨‍🦯

dry tendon
fickle knoll
#

now can somebody who isnt mad at me rn help me with my problem

low chasm
#

sure

polar acorn
gaunt swan
fickle knoll
#

so what can i write instead

low chasm
#

"i read it 5 times"

slender nymph
#

i don't know what your actual problem was, but you're moving via the transform so you aren't going to be respecting colliders

fickle knoll
#

but what word can i use so i respec colliders

polar acorn
fickle knoll
#

that dont help

#

I NEED PRECISE LINES OF CODE

#

or else my stupid brain cant understand

polar acorn
fickle knoll
#

yes

polar acorn
#

No handouts

fickle knoll
#

just this one time

polar acorn
#

no

fickle knoll
slender nymph
fickle knoll
#

.....

slender nymph
#

what a helpful response!

#

but for real, there are hundreds of tutorials for moving via character controller or rigidbody

fickle knoll
#

okay

#

👍

slender nymph
#

or if you really want to move via the transform, you can do even more work by checking for collisions manually using physics queries and the like

fickle knoll
#

dude i only understand half of those words

polar acorn
#

Then you should look them up

slender nymph
#

exactly. so go find some tutorials to copy from. or you can go through some beginner courses to actually learn wtf you are doing

dry tendon
#

i did that

slender nymph
dry tendon
#

what i dont understand is how can i access from pipes collision to a var on pipes controller...

#

probably its explained... but i dont get it

slender nymph
#

honestly for what you are doing you should learn how to use events because that would be the easiest way to do this

slender nymph
#

but your issue appears to be that you want to access a variable on your PipesController. not a variable on your prefab. go look at the other ways to reference the PipesController from the instantiated pipes

#

or just use an event like i suggested

polar acorn
empty sentinel
#

Hey I had some warnings I was trying to fix but clear on start was on and now there not there how do I find them again?

dry tendon
empty sentinel
polar acorn
#

If they don't come back, then problem solved

empty sentinel
#

But wait for what?

polar acorn
#

The warnings to come back

empty sentinel
#

And would a warning just fix itself like that if it didn’t come back?

slender nymph
#

it depends what the warning was

#

if it comes back, then you know you may need to address it. if it doesn't, then it likely was just a one time issue

empty sentinel
#

Well warning not error

polar acorn
slender nymph
#

then go to where the warning was pointing you to and fix it

dry tendon
# polar acorn What is it that you are trying to _do_

PipesController has got a var called hasCollisioned. I have another script that belongs to a prefab called PipesCollision, and i wanna make that hasCollisioned var true from the script PipesCollision. Is that clear?

empty sentinel
polar acorn
polar acorn
slender nymph
empty sentinel
slender nymph
#

in your IDE

#

surely it is configured so that you can see errors and warnings in the code

empty sentinel
#

Oh so VS?

slender nymph
#

yes

empty sentinel
#

Ok

unreal imp
#

hello freinds,can you guys help me improve my object grabbing code? (yes, again imitating half life 2), here it is: ```public class PickupableObjects : MonoBehaviour
{
[SerializeField] private LayerMask layerMask;
[SerializeField] private Camera PlayerCamera;
[SerializeField] private Transform PickupTarget;
[Space]
[SerializeField] private float PickupRange;
private Rigidbody currentObject;
private void FixedUpdate()
{
if (currentObject)
{
Vector3 directionToPoint = PickupTarget.position - currentObject.position;
float distanceToPoint = directionToPoint.magnitude;
currentObject.velocity = directionToPoint * 12 * distanceToPoint;
}
}
private void Update()
{
if (Input.GetKey(KeyCode.E))
{
Ray cameraRay = PlayerCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
if (Physics.Raycast(cameraRay, out RaycastHit HitInfo, PickupRange, layerMask))
{
currentObject = HitInfo.rigidbody;
currentObject.useGravity = false;
}
}
}
}

civic light
#

guys, quick question. Are these lines something that normally occurs?

#

well, lines

#

I can see that they're some sort of gaps that are opening in the tilemap? I'm not sure

eternal needle
slender nymph
civic light
unreal imp
rich adder
#

its just bricks but they're rb , you throw bricks and smash windows

unreal imp
#

ohhhhhhhh

#

so maybe changing the 12

rich adder
#

You want to see my script?

unreal imp
#

welp,ok

slender nymph
unreal imp
fickle knoll
#

you know what i will figure this out tommorow ty for the help

civic light
rich adder
rich adder
# unreal imp welp,ok
private void HoldObject()
    {
        Ray playerAim = playerCam.GetComponent<Camera>().ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        Vector3 nextPos = playerCam.transform.position + playerAim.direction * distance;
        Vector3 currPos = objectHeld.transform.position;
        objectHeld.GetComponent<Rigidbody>().velocity = (nextPos - currPos) * 10;
        if (Vector3.Distance(objectHeld.transform.position, playerCam.transform.position) > maxDistanceGrab)
        {
            DropObject();
        }
    }```
#

it can probably be cleaned up better(cache that rb/cam) , but I didn't have time to do so

rich adder
#

please use links for large code

unreal imp
#

what?

#

like a note blog?

rich adder
unreal imp
#

oh ok

rich adder
#

edit the msg with link

solar heron
#

Hey uh how do i make 1 player move with WASD and one move with Arrow keys

unreal imp
#

ok

rich adder
#

best using new Input System tbh

solar heron
rich adder
#

if not map each keycodes for each player

solar heron
#

hmm

rich adder
rich adder
civic light
# slender nymph then it's likely due to the zoom level in the editor. zoom all the way out in ga...

I know this might not interest you, but just in case, I found a fix to the problem I was having here: https://www.youtube.com/watch?v=Wf98KrAyB2I
I have no clue why it is that way, but it worked perfectly

How to fix tilemap tearing and edges/gaps in a 2D Unity Project is much simpler than you think and does not require reimporting or manipulation of any of your 2D assets, a simple Sprite Atlas is all you need and I'll show you how to do that in under 3 minutes. Tilemaps in a 2D Unity project can be quite frustrating but fixing them is easy. Plea...

▶ Play video
solar heron
unreal imp
rich adder
unreal imp
rich adder
rich adder
#

layers are bitmask not strings

#

use the struct made for it

#

LayerMask

#

besides that, does the code work?

unreal imp
rich adder
#

this makes no sense

#

why would you hold when its null lol

unreal imp
#

because if its not it will drop the object

#

If you don't have anything in your hand you can grab it, if not you will let it go that is 1 slot

rich adder
unreal imp
#

ok,only holding

rich adder
# unreal imp ok,only holding

heres what I had

if (Input.GetButton(GrabButton))
        {
            if (!isObjectHeld)
            {
                TryPickObject();
                tryPickupObject = true;
            }
            else
            {
                HoldObject();
            }
        }
        else if (isObjectHeld)
        {
            DropObject();
        }```
dull eagle
#

Hey everyone!

I'm currently making a bullet that slows and freezes the enemy whenever he is hit. The idea is that every enemy has a certain frost resistance, and each bullet shot removes that resistance by 1 while also slowing down the enemy for an x amount of time. When the frost resistance reaches 0, the enemy is frozen for an x amount of time.

I have the functionality basically working, but I can't figure out how I can extend the slow if the enemy is hit by a bullet before the last slow has run out. Since I'm using coroutines, it seems like the next coroutine doesn't get updated information from the last coroutine, so it only ever knows if the slow has already ended.

I would appreciate any help on how I could extend the slow by another x number of seconds when the enemy is hit before the slow has ended.

The game is 2D btw.

Here's the code:
https://pastebin.com/iXqPDbLB

unreal imp
#

im getting dizzy

rich adder
unreal imp
#

ok,i love you 😘

coral isle
#

hey there, can somebody help me a bit since I'm having trouble with raycasts? I'm never getting any hit information for some reason and I'm dumb. imma send the code in a sec

empty sentinel
#

Alright so I’m getting “The result of the expression is always ‘true’ since a value of type ‘OVRInput.Button’ is never equal to ‘null’ of type ‘OVRInput.Button?’”
When using “if (x.xInput != null)” How do I fix this?

slender nymph
#

x.xInput is a variable of a value type that is not nullable so it will never be equal to null. why are you trying to check it for null?

empty sentinel
slender nymph
#

so it's not even your code?

empty sentinel
#

No

slender nymph
#

then ignore it. it's just a warning anyway

empty sentinel
#

But it stops some things from working

slender nymph
#

it just means that statement will always be true, it's the equivalent of if(true)

slender nymph
empty sentinel
#

Oh well maybe I’m just dumb lol

coral isle
#

it takes from another script that is just used to get the navmeshagent and the animator components

#

that's not related though

#

the raycast never actually hits anything, even though I've made sure it's pointing the right way with a debug ray and there's also a bunch of other objects in between the one casting the ray and the target

#

it's also using a layer mask with all of the map and the target selected, without the parent object so it doesn't collide with itself

#

the ray shows that the direction is correct on this screenshot

#

(the white lines are the camera , the capsule is the player and the target)

slender nymph
#

what collider are you expecting it to hit and does that collider exist on a layer that is included in your layermask?

coral isle
#

I just realized testing now, apparently the ray is too low

#

when I jump on top of the thing it does register

slender nymph
coral isle
#

uhh how do I offset the ray origin a bit on the y axis? I'm so dumb sorry

queen adder
#

wrong chat im sorry

ivory bobcat
slender nymph
ivory bobcat
#
var origin = transform.position + offset;
var direction = (target.position - origin).normalized;```
#

Reminder that awake isn't the same as Awake

civic nacelle
#

I have a teleport script that worked, but when I updated untiy it caused it to stop working. When I try and teleport now it will take me to the location for a split second than take me back to the og postion.

dapper sinew
#

I am not a beginner in unity programming but I am in physics and that kinnd of thing so I think here is best. I am creating my own custom modular movement system and im working on my jump module currently. Here is my code

public class JumpModule : MonoBehaviour
{
    public bool isEnabled = true;
    public MovementManager movementManager;

    [Header("Customize")] public float jumpForce;
    public int maxJumps;
    public float jumpCooldown;
    private int jumpsRemaining;
    private float lastJumpTime = 0.0f;
    private bool isJumping = false; // Track if the player is currently jumping.

    public void StartJump(InputAction.CallbackContext context)
    {
        if (!isEnabled)
        {
            // Disable the script immediately if isEnabled is false
            enabled = false;
        }
        else if (jumpsRemaining > 0 && Time.time - lastJumpTime >= jumpCooldown && !isJumping)
        {
            // Call your custom logic method when isEnabled is true, there are jumps remaining,
            // the jump cooldown has elapsed, and the player is not already jumping
            Jump();
        }
    }

    public void Jump()
    {
        if (jumpsRemaining > 0)
        {
            movementManager.rb.velocity = new Vector3(movementManager.rb.velocity.x, 0.0f, movementManager.rb.velocity.z); // Reset vertical velocity.
            movementManager.rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            jumpsRemaining--;
        }

        lastJumpTime = Time.time;
    }

    public void Start()
    {
        jumpsRemaining = maxJumps;
    }

    public void Update()
    {
        if (movementManager.isGrounded)
        {
            jumpsRemaining = maxJumps;
        }

        Debug.Log(jumpsRemaining);
    }
}

In the update method I am setting the current amount of jumps I have to the max amount so it resets my jumps. The issue is that when I jump the first time I am grounded and so it immeditley resets the max jumps.

slender nymph
wintry quarry
#

This will avoid that kind of problem

#

You should also delay the force until FixedUpdate as well

civic nacelle
slender nymph
#

you should also have a way to tell the movementManager that it is no longer grounded when you start the jump

dapper sinew
dapper sinew
slender nymph
#

okay then you're going to continue being considered grounded until at least one frame has passed and the movementManager can update its own grounding status

dapper sinew
slender nymph
#

if you tell the movementManager that it is no longer grounded, then why would it be grounded when you check later that same frame?

dapper sinew
#

Because im not checking later on that frame, I would be checking on the same frame that i would tell the movement manager.

slender nymph
#

the same frame
later on that frame
that's the same thing

dapper sinew
#

Correct me if im wrong but thge movement manager would not be able to update in time before the player jumps.

slender nymph
#

what? just tell the movementManager that it is no longer grounded when you jump. then you will no longer be considered grounded until the movementManager checks for ground again. it's not that hard

dapper sinew
#

I agree that it's not very complicated, but the problem seems to be that you might not fully grasp what I'm trying to convey. Here's how my jumping mechanism functions:

Every frame, it checks if the player is currently on the ground. If they are, it resets the number of jumps available.

When the player attempts to jump, it checks whether they have any remaining jumps left. If they do, it applies the jump forces.

However, there's an issue when the player is on the ground and tries to jump. In this situation, the remaining jumps don't decrease after the first jump because the player is still considered to be on the ground, which resets the jump count. If I were to inform the movement manager that the player is no longer on the ground, this information would be immediately overwritten by the update function, which reports that the player is still on the ground.

slender nymph
#

so you know that you need to not be considered grounded. you also know that your movementManager checks for ground every frame (which is basically pointless, just do it on FixedUpdates since you are moving via physics anyway).
you were instructed to inform the movementManager that it is no longer grounded. knowing that it will check for ground again in that same frame, would the obvious solution not be to simply not check for ground in frames that it was told by outside sources that it is no longer grounded?

wintry quarry
#

You say you tried it but I'd like to see your try

#

Another missing piece here is how movementManager.isGrounded is calculated

#

because that may also be problematic

dapper sinew
# wintry quarry You say you tried it but I'd like to see your try

This is my update now for my is grounded

public void FixedUpdate()
    {
        if (movementManager.isGrounded)
        {
            jumpsRemaining = maxJumps;
        }

        Debug.Log(jumpsRemaining);
    }

this is my calculation for grounding

void FixedUpdate()
    {
        // Cast a ray from the center of the player's position downward to check for the ground.
        RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.down, out hit, groundCheckLength, groundLayer))
        {
            isGrounded = true;
        }
        else
        {
            isGrounded = false;
        }
    }

also for what boxfriend said is exactly what I want to acheive, which is not heck for ground in frames but I genuinely cannot think of a simple way to do this.

slender nymph
#

you've heard of if statements, right?

wintry quarry
dapper sinew
slender nymph
# dapper sinew Yeah now I know how to do it after thinking about it for a sec.

you should still take Praetor's advice though about making an IsGrounded method so you can ground check on demand instead of a potential execution order issue.
but you can also do exactly what I suggested too where your IsGrounded method can just return false if you ungrounded the object that frame. (you'd just need to make sure to reset whatever bool you are using either at the end of the frame or during the next one

slender nymph
#

instead of using a WaitForSeconds you could create your own timer using deltaTime and yield return null, then just add to the current duration

wintry quarry
wintry quarry
# dull eagle Hey everyone! I'm currently making a bullet that slows and freezes the enemy wh...

I'd probably do something like:

Queue<float> freezeCharges = new(); // keeps track of the time at which freeze charges were applied.

public void HitWithFreeze() {
  freezeCharges.Enqueue(Time.time + freezeDuration);
}

void Update() {
  // get rid of expired freeze charges
  while (freezeCharges.Count > 0) {
    float nextExpiration = freezeCharges.Peek();
    if (Time.time >= nextExpiration) {
       freezeCharges.Dequeue(); // the charge has expired
    }
    else {
      break; // we're done. The next expiration time hasn't come yet.
    }
  }

  if (freezeCharges.Count > 0) {
    // use slow speed
  }
  else {
    // use normal speed
  }
}```
dull eagle
#

I guess I just have to drop the coroutines

thick goblet
#

https://hatebin.com/oykiqzmuqb How do I make my 2D asteroid object which moves straight to the left Rotate on the Z axis slowly without it disturbing the movements direction? I used many rotates but they always mess up the asteroids movement left path?

slender nymph
#

ah wait, discord formatting kind of fucked up that if else. no infinite loop

wintry quarry
#

the only reason we need the queue is if you wish to display the number of freeze charges in the UI

#

or really, if you need the actual number of charges for any reason

#

if you just want to know when you're at zero (which currently seems to be the implementation), then yeah there's no need to track the number of charges and you can just use an "unfreeze at" time

slender nymph
thick goblet
#

Yeah I changed the movement to rb.velocity

#

Wooooo my asteroids are spinning!

#

Thanks a lot

dull eagle
steady forum
#

What’s the best way to learn C# for unity that helped y’all the most?
Just now learning about a month ago.

slender nymph
#

there are beginner c# courses pinned in this channel. though I personally recommend the book The C# Player's Guide by RB Whitaker. it's a great resource for learning c# in a decently gameified way

rich adder
steady forum
#

@slender nymph @rich adder thank you!
I’ve been watching brackeys beginner course and a couple others.
Was debating on a good book but get mixed views.
Want to mainly use c# for gaming of course but would love to learn in full in the end.

rich adder
#

brackys is the worst for c#

summer stump
steady forum
#

@rich adder @slender nymph
Okay thank you. Brackeys was the only one I knew off top.
My current course is by learn, play, create

empty juniper
#

i have a scirpt that references a bool from a diff script but i cant drag and drop the script into the feild in the inspector

summer stump
icy wave
#

Is the script you need a bool from attatched to a gameobject or is it standalone?

empty juniper
summer stump
icy wave
#

You can't reference a script itself in the unity editor (unless it's attatched to something) if you want to reference a script itself, the class needs to be static, and the bool needs to be public

empty juniper
summer stump
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

icy wave
#

For example:

public class myClass 
{
  public static bool PossiblyDestroyObject(parameters) 
  {
    logic
    ...
    return shouldDestroy (where shouldDestroy is a bool);
  }
}

You can then call this function by doing:

bool shouldDestroy = myClass.PossiblyDestroyObject(insert parameters);
coral isle
#

ok so I the after fixing the raycasting there was a new problem and this one is truly weird at least for me

#

so I have this character that's basically a capsule that's on his scene and he can move and jump and everything

#

but when I move it to another scene the jump refuses to work, it either doesn't jump or jumps but continues to go up infinitely

#

imma post the code for the movement script in a sec, but it shouldn't really change with the scenes

#

it was writter (probably stolen) by a friend so I don't 100% understand it and can't tell what's causing the issues

rich adder
coral isle
#

also taking the character from another scene was needed because on the one I'm working it just broke after changing the layer from layer 8 (map) to 9 (player)

#

idk why my friend had it set up that way but I needed to change it to use a raycast layer mask

#

and changing the layer also breaks it on the scene where I'm taking it from

#

I honestly have no idea what could cause this

teal viper
# coral isle https://paste.ofcode.org/MZsdNTRzTqkecZqPiA5t8p

Read the code.
Start from the end of the issue.
Since it's related to movement, check the movement vector you pass into _controller.Move. It probably has a vertical velocity.
After confirming it, break it down and see where that vertical velocity is coming from.

rich adder
teal viper
#

Debug with a breakpoint ot logs to see the values.

coral isle
#

alright, apparently the sphere to check whether it's on the ground or not is having a stroke and detecting other parts of the character

rich adder
#

those parts are probably part of the checklayers

coral isle
#

can you use layer masks for sphere checks as in raycasts?

rich adder
#

yes you can use layermask

coral isle
#

that should save me the trouble of having to change it too much

#

all right it now works

#

now I gotta copy it over to the other scene and pray

#

thanks guys

grim tulip
#

How woukd I learn to code with the Unity engine?

teal viper
#
  1. Learn to code with C#
  2. Learn unity API and workflow
north kiln
#

There are resources pinned to this channel

atomic perch
#

Say I have a vector3 point in world space and an array of 8 corners of a 3d shape also in world space. Is there an easier way of determining whether the point is inside those spaces than calculating all 6 planes? This is what I currently have but it doesnt seem to be returning true for points that certainly lie within the shape

    {
        // Check if the frustumCorners array has the expected length (8 corners)
        if (frustumCorners.Length != 8)
        {
            Debug.LogError("Invalid frustumCorners array length.");
            return false;
        }

        // Define the six planes that make up the frustum
        Plane[] frustumPlanes = new Plane[6];

        // Calculate the frustum planes using the corners
        for (int i = 0; i < 6; i++)
        {
            Vector3 a = frustumCorners[i];
            Vector3 b = frustumCorners[i + 1];
            Vector3 c = frustumCorners[i + 2];

            frustumPlanes[i] = new Plane(a, b, c);
        }

        // Check if the point is in front of all six planes
        for (int i = 0; i < 6; i++)
        {
            if (frustumPlanes[i].GetDistanceToPoint(point) < 0)
            {
                // The point is behind this plane, so it's outside the frustum
                Debug.Log("Not in frustum");
                return false;
            }
        }

        // If the point is in front of all six planes, it's inside the frustum
        Debug.Log("Is in frustum");
        return true;
    }```
#

I have a feeling its due to the order of the points, should I go be going clockwise front to back?

gaunt ice
#

i may consider using normal and dot product for testing

#

btw your vertices is unordered, no way to construct the 6 planes

timber tide
#

Is this for a camera frustum?

#

there's some utility library for that, but perhaps it could be used for this problem too

atomic perch
timber tide
atomic perch
#

Oh this should still work, I'll take a look and try wrap my head around it further

frozen mantle
#

btw, thanks for the heads up on this, now im only allocating 1 string instead of like, 3-5

#

so, im getting a weird issue, where whenever i boot up my unity project and run it, the logic for my game manager goes wonky

#

like, it will work perfectly yesterday, and then when i boot it up for the day to work on my project, the logic will break

#

and it doesn't fix itself until i go ahead and delete the and reinsert the script into the scene

frozen mantle
#

Okay and now it's doing it everytime i reboot unity, instead of when i reboot my PC?

#

what is going on with my script??

summer stump
frozen mantle
#

i do use git but i haven't done any commit in a while, none of my scripts are being reverted or anything

frozen mantle
#

i haven't commited anything in about 2 months tho

summer stump
#

That's a long time to go without commiting haha

frozen mantle
summer stump
#

Oooh, fair. I had assumed there were a lot of built up changes.

frozen mantle
#

what's weird is that it seems the script only breaks in the new scene i made for the first level, it doesn't break in the testing/sample scene i made to code up the game logic and stuff

#

and as i said, the script works when i delete it out of the scene, and then reinsert it back into the scene

summer stump
frozen mantle
frozen mantle
coral isle
#

I am almost finished with my basic AI

#

that is due tomorrow !!!!

#

I had to redo the whole script because my friends are dumb

#

anyways does anybody know how do I stop a collider from bumping into things? if I can do that then the only thing left will be the animations which are not my job

coral isle
summer stump
#

if you do a trigger, you can get the OnTriggerEnter message if you'd rather, but you'd also fall through the ground of course.

coral isle
#

shouldn't different colliders be able to overlap?

summer stump
#

A non-trigger collider should be roughly the same shape and size as the modle

summer stump
frozen mantle
# frozen mantle so basically, the part that's break specifically is the gun inventory of my game

basically, i have 8 guns in my game, and the way the game manager keeps track of what the player has or doesn't have is to initialize an array of 8 bools that represent each gun (true = have, false = no have)

basically, in edit mode, i set the initial "starting" weapon by enabling it's view model on my player, and then when i enter play mode, my Player script first sees which weapon in the viewModel list is enabled, and sets that as the Current Gun. It then enables all of the viewModels to wake up all of the guns' scripts so that my game can keep track of their ammo counts. Is then disables all the weapons, and only reenables what's supposed to be the current gun. The player script then calls upon the game manager to add the starting weapon to the list of 8 bools by setting the current gun's corresponding index in that list to true. In the Game Manager's script, when i first enter play mode, it just adds 8 false bools to populate the list. The bug im having (and the part of the logic that is breaking) is that the player script is not able to properly read the GameManger's gun list or something, and when it tries to Add the default weapon to the gun inventory, it just sees an empty list, and the method fails. This doens't crash the game, only leads to the undesired behavoir of being able to switch forward (but not backward, for some reason...) only between the first and last weapons of the total gun list.

#

@summer stump That's the best way i can describe how my weapon system works atm, it's confusing i know, but it works!... at least until now

summer stump
coral isle
#

at this point it might as well just be easier to use raycasts for what I want to do honestly

summer stump
frozen mantle
#

yeah, i had debugs in my code, but for some reason i removed em because the bug went away

summer stump
# coral isle at this point it might as well just be easier to use raycasts for what I want to...

Raycasts are great for sure, you should definitely use them IN CONJUNCTION with a collider.

Is your rigidbody kinematic, or do you even have one? If you have one and it's not kinematic, you'll need a collider. or you'll just fall through the ground

I mean, a collider is gonna just... do the work for you. Otherwise you need to write a ton of code to get the raycasts to work with not walking through walls and stuff.

frozen mantle
#

now that it's back i gotta find out where the hell i put the debug logs, lol

summer stump
coral isle
summer stump
#

You don't have a character controller on it do you? Those contain a collider already, and shouldn't be on the same object as a rigidbody.

Just checking.

coral isle
#

oh wait I forgot to tell

#

the character with the big hitbox is the one checking for collisions and not the player

#

maybe I should give the big hitbox to the player now that I think about it

summer stump
frozen mantle
#

@summer stump found my issue, for some reason, when i load the scene in the editor, it makes it so that the player script awakens first, before the gameMananger awakes and sets up the array of Bools. Basically when i try to add my defaultGun, it's accessing an empty array because the array hasn't been initialized yet

#

for some reason, loading the scene messes with the boot order of my object it seems

#

and the boot order gets "corrected" when i delete and reinsert my game manager script

summer stump
coral isle
frozen mantle
#

this project is a year old (i know, long for a "test" project but im learning, okay?) and always had more than 1 scene

summer stump
frozen mantle
#

how come now the execution order is all jumbled?

#

i see, alright

#

so the solution is to move my gamemanager stuff from awake to Start on my player script

#

well at least im learning this now

#

before things got really complicated

summer stump
charred spoke
frozen mantle
#

damn

charred spoke
#

You probably added more scripts that made the order more random

#

Note Awake will always be called before Start its two of the same type that are not guaranteed unless you specify it

#

So Awake from script A might run before Awake from Script B

#

Or it could happen the other way around

timber tide
#

player script should probably be start while the gamemanager should usually be awake

#

anything non-dependent in awake

coral isle
#

ok so remember when I said that the trigger colliders weren't working? I was dumb

#

I use a OnCollisionEnter instead of an OnTriggerEnter

#

that just goes to prove how dumb I am

frozen mantle
#

ok, i see, thanks for the help guys, i appreciate it alot

#

@timber tide @charred spoke @summer stump You have expanded my Unity Knowledge

coral isle
summer stump
frozen mantle
#

yup, changing non-dependent calls to start() fixed it

#

yay

#

whew, that was making me pull hair a bit i won't lie

silent idol
#

very fast ask here, how do I compare the contents of an array to another array?

#

I forgot how to do it

#


    void CompareMyFlags()
    {

        string[] arrayOfPossibleFlagsReached = flagContainer.possibleFlagsReached.ToArray();

        if (arrayOfPossibleFlagsReached.Length == 0)
            Debug.LogError("There's nothing to scan, chief!");

        for (int i = 0; i < arrayOfPossibleFlagsReached.Length; i++)
        {

            for (int j = 0; j < flagContainer.allMyFlags.Length; j++)
            {

                Debug.Log(flagContainer.allMyFlags.ToString());

                //if i==j, break

                while(flagContainer.allMyFlags != arrayOfPossibleFlagsReached)
                {

                    
                    Debug.Log("");
                    break;


                }


            }```
eternal needle
# silent idol very fast ask here, how do I compare the contents of an array to another array?

kinda hard to understand the code since most of the variables arent shown, but you dont need 2 for loops here. if you are just comparing both arrays, you want to run through both once (and its up to you for what you want to do if they are different lengths).
Just store the length of one array, then run through both like arrayOfPossibleFlagsReached[i] and flagContainer.allMyFlags[i]

silent idol
#

So... each string must match up exactly

#

Like the flag system is used to mark if quests are finished or not

#

so my system needs to look for eg. 'Egg' in the allMyFlags and compare it to arrayOfPossibleFlagsReached for the value of 'Egg'

coral isle
#

do yall think this loading bar will ever complete or will I have to redo the last 3 hours because I haven't saved in a while?

silent idol
#

Let me show the whole code here

coral isle
eternal needle
# silent idol so my system needs to look for eg. 'Egg' in the allMyFlags and compare it to arr...

it doesnt really sound like you need to use both arrays in this case, im not sure what you would even be comparing it for. one has all flags, and another is the flags reached. All flags sounds like it holds every single one, so the only thing you'd be searching for is the index.
Although there is probably way more to this than just "compare contents in arrays" because i dont know what you intend to do with this

#

"compare" is a very general term

eternal needle
cosmic dagger
coral isle
#

beyond fucked

silent idol
# eternal needle it doesnt really sound like you need to use both arrays in this case, im not sur...

It triggers and ties into an event system.

Event system sends call to add entry to myFlags array in the SO, or compare both arrays together.

AllPossibleFlags reached stores all flags in the chapter on a SO. Myflags is what flags have been reached and stored by the player. Upon reaching a 'gateway', the flagChecker is supposed to recieve a call from Event system. It will scan the myFlags array for all possible flags and compare them to the flags in allPossibleFlags.

Once it finds a match, it will trigger the appropriate event.

eternal needle
# coral isle this?

yes, you can just change the name and then check if its more recent than whats saved inside unity. your code though is unrelated and will have been saved already by you

coral isle
#

you're a lifesaver

#

thanks

silent idol
gaunt ice
#

dictionary or hashset supports o(1) add,remove and lookup

eternal needle
coral isle
#

ok something has to be causing this imma undo some bits of code

#

at least I do have the scene

eternal needle
silent idol
#

true

coral isle
#

is there something against while loops ? that seems to be the cause of the bug

eternal needle
#

although i still dont know what you're actually trying to compare

silent idol
#

What's a more robust system? I'm wondering if dictonaries will be less prone to corruption but IME they're super hard to add too and remove.

silent idol
#

That's the gist of it

#

Or

#

If (A = B && C = D)
{Scene E}

charred spoke
silent idol
#

can have multiple flags that are compared or just 1

#

Although it's got pretty huge potential to get messy so I'm trying to build good framewor

coral isle
charred spoke
#

Yes and no?

coral isle
#

it is in a void FixedUpdate

#

but it's in a part that should only execute once

eternal needle
coral isle
#

and then wait a bit

coral isle
eternal needle
charred spoke
#

Okey so same thing. Think about what is happening. A while will repeat the code inside it WHILE the condition is true. So your agent is <3d from his destination you set a new destination then it goes to the check again and it is still <3f the game has not progressed. FixedUpdate is already a kind if while loop so you dont need it just change the while to a if

silent idol
#

So basically like I'm most RPGs they have a quest system that determines if you've completed certain objectives and have certain items in your inventory before you can go to the next stage?

That.

#

I'm essentially making a system that checks if you have item A, B and C, before you can progress to area D. If not, you go to area E.

cosmic dagger
silent idol
#

This

Essentially

#

Courtesy of my kitty chalkboard

eternal needle
#

it doesnt really make sense what you are comparing the 2 arrays for, like you have A in one array and are trying to find it in the other?

silent idol
#

Yes

#

I have A in the allPossibleFlags array

coral isle
silent idol
#

and I'm trying to look for A in myFlags

coral isle
#

and maybe even a third time if my luck sucks

silent idol
#

I had to convert the list to an array because I don't think there is a way to compare lists to arrays

gaunt ice
#

why are you compare list to array, you want to compare the element in array to element in list

silent idol
#

I'm converting the list into a format where I can compare it to the array

cosmic dagger
eternal needle
cosmic dagger
silent idol
#

So convert both ```cs
public List<string> possibleFlagsReached = new List<string>();

public  string[] allMyFlags;```

To a dictionary

gaunt ice
#

idk why you call tostring in string actually...

eternal needle
#

You have a list of string and a string array, you dont need to convert a string to string

silent idol
#

But I'm not sure how I would handle adding flags to the dictionaries. See, flags are added to the allMyFlags depending on certain actions the player takes... I don't know if it's possible to add and minus from a dictionary in such a way.

coral isle
#

imma just go to sleep since it's almost 5am

gaunt ice
#

you can remove key from dictionary ....

coral isle
#

have a nice day or night or whatever

#

bye and thanks for helping me today

cosmic dagger
silent idol
#

It wasn't possible to get a debuglog of the array unless I did a .tostring

eternal needle
#

You should probably look at the basics of c# first because honestly this approach seems very fragile/unnecessary. Maybe due to not being experienced with collections

silent idol
#

To get the value inside the array

#

If not, I just get the array itself

silent idol
#

I am using an events systems

gaunt ice
#

do you know how to get array element?

silent idol
#

It's just not implemented yet, I'm trying to make this thing work

silent idol
#

I know it's fragile but there aren't that many other ways due to time constraints

#

i don't have a year to relearn C#

eternal needle
#

Itd probably be easier for all these flags to just be bools somewhere. Or a bitmask

silent idol
#

I need to get something reasonably functional out the door by the end of this year

#

Yeah the original idea was using a dictionary and a hex value to refer to each flag

#

but I don't think it's very agile because I have trouble calling the dictionary

eternal needle
#

Mess around with a dictionary outside of unity. It's very easy to use. Although I dont know what you plan to use the dictionary for either

#

Like the key would be the flag name then the value would be if they completed this objective?

silent idol
#

Something Like

'0001DOOR' == true/false
'0002ROOM' == true/false

#

Yeap

#

So either I store all the values per chapter in a dictionary on the scriptable object, then on the correct event, the event manager pings the dictionary to change the bool value

#

Wait uh, I think this seems like a pretty good solution

eternal needle
#

That would at least get rid of the 2 arrays existing

silent idol
#

Just scan the dictionary for '0001DOOR' == true and '0002ROOM' == false at the relavant checkpoint

#

ok thanks

#

I think

this actually solved quite a bit of the problem

eternal needle
#

You dont need to "scan" the dictionary, it has a O(1) lookup meaning its constant time

cosmic dagger
charred spoke
eternal needle
silent idol
#

true

#

So I'll just need to access several keys in the dictionary at relavant points

#

and check if the bools are true

#

if true, play scene D

#

if false, play scene E

eternal needle
silent idol
#

I'm just wondering if it's possible to turn a dictionary into a SO where each chapter contains a seperate data set, or a dictionary spans all chapters?

#

Like, a SO for just chapter 1 flags, chapter 2 flags... etc.

eternal needle
#

You are gonna have to construct the dictionary from some data, if that data is stored in an SO that's fine. The SO can be used to just create your quests, where you store the flags you want completed on them

#

If that's what you're asking

silent idol
#

i see

coral isle
silent idol
#

so all dictionary data will encompass the whole game?

#

cant split it up into multiple scriptable objs?

cosmic dagger
eternal needle
#

Depends how you want to do it, you could have many small dictionaries or 1 massive one

silent idol
#

i see

eternal needle
#

It shouldnt really matter, but if you have a small dictionary only containing the exact same thing as 1 list then you likely dont need a dictionary

#

You could just add to a counter at that point and check if the counter equals the list length

silent idol
#

it should be about 200 strong

#

at the end of the game

frozen dagger
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

prisma blaze
#

how can transform have a reference to the gameobject and vice versa? wouldn't that lead to a circular reference?

swift sedge
keen dew
#

Yes it does, and no it's not a problem

frozen dagger
prisma blaze
swift sedge
prisma blaze
keen dew
#

nope

frozen dagger
prisma blaze
#

so having a circular reference isn't a problem at all?

keen dew
#

correct

prisma blaze
#

thanks, i remember got a circular reference error when doing web dev so i thought it'd be the same here too

keen dew
#

I mean it can be a problem in some situations like serialization, but as a general concept no

prisma blaze
#

oh yeah

#

it was a serialization problem

#

thanks again

swift sedge
#

what, transform.gameObject?

#

well, its useful having it...

prisma blaze
#

yeah i thought having circular references is not possible that's why i asked

gaunt ice
#

why it is not possible.....it is just a graph with cycle, and requires guard on serialization to avoid visiting same vertex twice

swift sedge
frozen dagger
#

(i watched random youtube tutorial lol)

swift sedge
#

It's tagged as insecure and untrusted by microsoft

#

and shouldn't be used for new projects

#

you can still use it, but everyone will say that you shouldnt...

fickle plume
#

Or rather consider that arbitrary code can be injected into it, malware for example, and executed at runtime.

fickle plume
#

yes

swift sedge
#

thats why most games just use databases to save data

#

... or use a safe binary serialization option like Binary Writer

fickle plume
frozen dagger
#

thx

#

i will not use binary formater on data cuz i want to make secret ending what can be found only by editing game data

fickle plume
#

if you want easy readable save you can use NewtonsofJson which is used by unity internally as well

fickle plume
swift sedge
#

so it should be ok

fickle plume
#

yep

delicate portal
#

Hey how can I reference to this?

fickle plume
fickle plume
delicate portal
#

I can reference to it as a playable asset tho

fickle plume
#

You should be able to see in the inspector what that is

delicate portal
short hazel
#

Another way would be to drag-drop it into a field of type Object, call .GetType() on it, and log the result

fickle plume
quaint thicket
#

Could someone assist me with my 3rd person camera? The camera does not rotate vertically and my attempts to fix it cause the camera to get lopsided.

        public static float rotationX = 0;
        public static Vector2 rotationLimits = new Vector2(80, -80); // Vertical rotation limits
        private static Vector3 offset = new Vector3(0f,0f,0f);

        void RotateCamera4(float x, float y)
        {
            Transform target = Object.PlayersMainObject[0].GameObject.transform; // It's just a GameObjects Transform.

            // Get the mouse input
            float mouseX = x * 2f;
            float mouseY = y * 2f;

            // Rotate the target horizontally
            Camera.main.transform.Rotate(Vector3.up * mouseX);

            // Rotate the camera vertically
            rotationX -= mouseY;
            rotationX = Mathf.Clamp(rotationX, rotationLimits.y, rotationLimits.x);
            Camera.main.transform.Rotate(Vector3.left * mouseY); // My attempt

            // Calculate the rotation quaternion
            Quaternion rotation = Quaternion.Euler(rotationX, target.eulerAngles.y, 0);

            // Calculate the new position of the camera based on the rotation and offset
            Vector3 newPosition = target.position + rotation * offset;

            // Apply the new position to the camera
            Camera.main.transform.position = newPosition;

            // Make the camera look at the target
            Camera.main.transform.LookAt(target);
        }```
silent valley
#

This is attached to my Sniper weapon prefab which has a chance of spawning when killing an enemy. The "Camera Zoom" is attached to my main camera. Is there a way to automatically access the Camera zoom when the prefab spawns? I thought this would of worked but it doesnt

#

This is my error and I'm struggling to figure it out

fossil drum
trail creek
fossil drum
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

trail creek
fossil drum
quaint thicket
#

I can certainly switch to using Cinemachine but I like to do a simple code first to understand.

young warren
fossil drum
young warren
#

Since Camera zoom is on your camera, get a reference to your camera first then GetComponent on that

silent valley
young warren
#

You should check the pins for the link on referring to members on other scripts

quaint thicket
fossil drum
silent valley
fossil drum
quaint thicket
trail creek
prisma blaze
#

can someone help me with this? i'm trying to spawn these cubes in a plane, but the code i found seems to not work correctly? i'm spawning about 300 green and 300 red cubes just to test, but they seem concentrated on those spots, is this normal ? do i have to code in logic that spreads them?
here's the code ```csharp
public void SpawnCollectables(int number, GameObject plane)
{
var planeMeshRenderer = plane.GetComponent<MeshRenderer>();
var SpinningBoxScript = SpinningBoxPrefab.GetComponent<SpinningBox>();
float x_dim = planeMeshRenderer.bounds.size.x;
float z_dim = planeMeshRenderer.bounds.size.z;
x_dim /= 2;
z_dim /= 2;
SpinningBoxScript.material = CollectableMaterial;
SpinningBoxScript.Type = "Collectable";
for (int i = 0; i < number; i++)
{
SpawnSpinningBoxAtRandomPosition(plane, x_dim,z_dim);
}
}

private void SpawnSpinningBoxAtRandomPosition(GameObject plane, float x_dim,float z_dim)
{
    GameObject obj = Instantiate(SpinningBoxPrefab, UnityEngine.Vector3.zero, UnityEngine.Quaternion.identity, plane.transform) as GameObject;
    var x_rand = Random.Range(-x_dim, x_dim);
    var z_rand = Random.Range(-z_dim, z_dim);
    z_rand = x_rand > z_rand ? Random.Range(0, z_rand) : Random.Range(0, x_rand);
    obj.transform.position = new Vector3(x_rand, BoxHeight, z_rand);
}
trail creek
#

ok, changed it

fossil drum
quaint thicket
trail creek
#

@fossil drum i solved it but ty

nocturne parcel
#

How do I hide an inherited variable on the inspector from the subclass, but let it show on the base class?

#

I.E hide this

#

But show this

short hazel
#

With a custom inspector for the subclass

nocturne parcel
quaint thicket
#

@fossil drum You're right, cinemachine makes things so much easier. I got my camera to work fine now.

cunning mesa
#

Are there 2D versions of the navmesh agents for pathfinding?

young smelt
#

please where do I go to ask about a bad baking result

young smelt
#

ok, tnks

vocal marlin
#

apparently if you destroy things in a grid layout group, on mouse down doesnt work on them but on mouse enter does???

#

does anyone know why this happens?

#

if you set the parent so something else it works fine; if you add a crad it wroks fine but destroying them directly does some wierd stuff for no reason

#

if you need to see my scripts i can show you them and gie an example of what i mean

hollow zenith
#

What is the easiest/simplest way to implement a basic save system in Unity that works on mobile and PC?
I just need to save a JSON format ideally, but anything else works.
it's just some numbers(indexes from array and "levels" or "gold/currency")

It has to work with multiple save slots, but I think that is no issue once the basic system is in place.

short hazel
#

Integrated JsonUtility can do basic serialization

#

There's Newtonsoft.Json, more potent but it's a package to install

#

File interaction can be done with the stuff in System.IO

hollow zenith
#

I think the JsonUtility is enough, I will probably create a "save" class" and add data to it when I save the game.

south socket
#

Hey everyone,

I am working on a VR environment, I used Google Cardboard XR Plugin for Unity, it is going really well but I am having one issue where the cardboard Reticle pointer is not staying in the middle, it is dynamically moving left/right/up/down when I tilt my head, this is causing misalignment with the logic itself and recognizes objects incorrectly. Attaching photos for more context.

If anyone has any experience on how to solve this would really appriciate it...

hollow zenith
#

Alright System.IO seems like what I need, thanks.

tawdry bear
#

Hi, I've been trying to figure this out for literally 24 hours. I'm completely new to Unity and coding and is desperate. Please help me...

I've been trying to follow this tutorial: https://www.youtube.com/watch?v=0T5ei9jN63M

🤖 Play Web Version: https://unitycodemonkey.com/unityPlayer.php?v=0T5ei9jN63M
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=0T5ei9jN63M
In this video we're going to make a Health System and a visual Health Bar.
It's going to be a clean and independent class that we can apply to anything like the player, enemies...

▶ Play video
#

These are my scripts

#

I made sure patience bar is arranged accordingly in hierarchy

#

But my health bar just isn't moving, does anyone know why?

#

According to my debug, the bar is supposedly moving, and the patience percentage is calculating accordingly - but the bar itself just isn't moving

short hazel
#

You already asked this in another channel, please don't cross-post

tawdry bear
#

Oh sry 😓

south socket
#

@short hazel Do you mind reviewing my question, just to make sure it's suitable for this channel or should I use another one

somber wren
#

i need help; i can't figure out where the problem is :')

short hazel
#

Depends if you have code that moves it or not

south socket
#

Thank you! I am using Google's scene but as you mentioned I just modified the script and made the dot in center at all time, just removed the dynamic piece altogether 😄

grim tulip
#

I think I fount the most helpful yt playlist for people to learn how to code(maybe)

deft yacht
#

Hey sorry guys, im new to unity and Im getting these errors, its an older version of unity. i didnt wanna risk updating the project to a newer one and breaking it so i kept it in its original version, i think these have to do with Dotween?? but theres 162 of them 🥺

wintry quarry
#

I recommend updating both to the newest version

languid spire
deft yacht
#

upgrade or downgrade? since the version of unity is 2k19

wintry quarry
#

Upgrade

#

You are using version control yes?

#

Aka Git or PlasticSCM?

#

If so there's no risk in upgrading since you can revert at any time

#

If you're not using version control you need to start

deft yacht
#

ahhh okayy, ill see if upgrading works

queen adder
#

Hi

Im trying to Flip my Gameobject who is a Child of my Parent "Player" but my code doesn't work with it

    void Flip(float _velocity)
    {
        if (_velocity > 0.3f)
        {
            GameObject.flipX = false;
        }
        else if (_velocity < -0.1f)
        {
            GameObject.flipX = true;
        }
    }
wintry quarry
queen adder
#

Yeah i was writing it sorry ^^

wintry quarry
#

What is GameObject here? Seems like it's the class name of GameObject but your code implies it's a SpriteRenderer, which is super confusing.

queen adder
#

for now, im trying to use the code i used, for flip my spriterenderer, i don't realy know how should i flip my GameObject with the "Player"

wintry quarry
queen adder
#

yep

wintry quarry
#

not sure what the picture is supposed to be showing.

queen adder
wintry quarry
#

I don't see where you got the idea that GameObject was appropriate here at all

#

so your issue is you are using the flipX property on your sprite renderer

#

all that does is draw the sprite in reverse

#

it doesn't actually rotate your object

#

so anything else on it will not rotate, including child objects, etc.

#

I recommend rotating the actual object instead of using SpriteRenderer.flipX

#

Rotating a GameObject is done via its Transform component

#

e.g.

// flipped
transform.eulerAngles = new Vector3(0, 180, 0);

// normal
transform.eulerAngles = new Vector3(0, 0, 0);```
short hazel
#

Your velocity might never be negative as well, if it's a result of calculating a vector's magnitude

queen adder
vernal sequoia
#

Can someone explain pls why my renderer bounds are behaving so strangely? I will be looking forward to your help.

using UnityEngine;

public class DrawRendererBounds : MonoBehaviour
{
    // Draws a wireframe box around the selected object,
    // indicating world space bounding volume.
    public void OnDrawGizmosSelected()
    {
        var r = GetComponent<Renderer>();
        if (r == null)
            return;
        var bounds = r.bounds;
        Gizmos.matrix = Matrix4x4.identity;
        Gizmos.color = Color.blue;
        Gizmos.DrawWireCube(bounds.center, bounds.extents * 2);
    }
}
        Renderer renderer = gameObject.GetComponentInChildren<Renderer>();

        if (renderer == null)
        {
            Debug.LogWarning("Renderer component not found.");

        }

        Bounds bounds = renderer.bounds;
        float rayLength = bounds.size.y;

        Vector3[] topCorners = new Vector3[4];
        topCorners[0] = new Vector3(bounds.min.x, bounds.max.y, bounds.min.z);
        topCorners[1] = new Vector3(bounds.max.x, bounds.max.y, bounds.min.z);
        topCorners[2] = new Vector3(bounds.min.x, bounds.max.y, bounds.max.z);
        topCorners[3] = new Vector3(bounds.max.x, bounds.max.y, bounds.max.z);

        Vector3 topLeftCorner = topCorners[0];
        Vector3 topRightCorner = topCorners[1];
        Vector3 bottomLeftCorner = topCorners[2];
        Vector3 bottomRightCorner = topCorners[3];
wintry quarry
short hazel
wintry quarry
#

Looks perfectly fine in this image

#

Are you aware that bounds are expected to be this way? Bounds are "AABB"s aka "Axis Aligned Bounding Boxes". Note the "Axis aligned" part - illustrated perfectly by the image.

vernal sequoia
wintry quarry
#

they are bounding the object perfectly

queen adder
short hazel
#

Only if the game starts by immediately kicking the player backwards

vernal sequoia
short hazel
#

If the player does not move, the velocity will be at 0, and neither if statements will pass

vernal sequoia
#

oh... i see...

#

ty very much, i will kill myself rn because of this xD
In my project, the object did not change its rotation, and now that I have added it, the render bounds have shifted)

#

Is there any other type of bounds? Like collider bounds?

wintry quarry
#

all Bounds are axis aligned

#

what are you trying to do

vernal sequoia
#
using Unity.VisualScripting;
using UnityEngine;
public class GroundChecker : MonoBehaviour
{
    public LayerMask groundLayer;
    public LayerMask baseLayer;
    private bool isGroundedResult = false;
    public bool IsGrounded(GameObject gameObject)
    {

        Renderer renderer = gameObject.GetComponentInChildren<Renderer>();

        if (renderer == null)
        {
            Debug.LogWarning("Renderer component not found.");

        }

        Bounds bounds = renderer.bounds;
        float rayLength = bounds.size.y;

        Vector3[] topCorners = new Vector3[4];
        topCorners[0] = new Vector3(bounds.min.x, bounds.max.y, bounds.min.z);
        topCorners[1] = new Vector3(bounds.max.x, bounds.max.y, bounds.min.z);
        topCorners[2] = new Vector3(bounds.min.x, bounds.max.y, bounds.max.z);
        topCorners[3] = new Vector3(bounds.max.x, bounds.max.y, bounds.max.z);

        Vector3 topLeftCorner = topCorners[0];
        Vector3 topRightCorner = topCorners[1];
        Vector3 bottomLeftCorner = topCorners[2];
        Vector3 bottomRightCorner = topCorners[3];

        bool topLeftHit = Physics.Raycast(topLeftCorner, Vector3.down, rayLength, groundLayer);
        bool topRightHit = Physics.Raycast(topRightCorner, Vector3.down, rayLength, groundLayer);
        bool bottomLeftHit = Physics.Raycast(bottomLeftCorner, Vector3.down, rayLength, groundLayer);
        bool bottomRightHit = Physics.Raycast(bottomRightCorner, Vector3.down, rayLength, groundLayer);
        isGroundedResult = topLeftHit && topRightHit && bottomLeftHit && bottomRightHit;

        return isGroundedResult;
    }
#

like this

#

I get the top corner points of the object and shoot a ray down from them

wintry quarry
#

bounds is overkill for this

vernal sequoia
#

But what method can be used to solve this situation?

#

like idk, mb another bounds?

wintry quarry
#

oh i thought you figured it out

#

a few options

#
  1. Use empty child GameObjects at the positions you want
  2. get the corners you want with like
Vector3 topRight = transform.TransformPoint(new Vector3(0.5f, 0.5f, 0.5f));
Vector3 topLeft = transform.TransformPoint(new Vector3(-0.5f, 0.5f, 0.5f));
Vector3 bottomRight = transform.TransformPoint(new Vector3(0.5f, 0.5f, -0.5f));
Vector3 bottomLeft = transform.TransformPoint(new Vector3(-0.5f, 0.5f, -0.5f));```
vernal sequoia
wintry quarry
#

wdym by change in size of the object?

#

If you are changing the size via localScale, then the transform.TransformPoint approach will already take that into account

vernal sequoia
#

hm

#

For example, in the Inspector I changed the height of the object. Now my ray does not reach the ground, because it hit a certain length, tied to a variable. This means that you will also have to change the value of the variable

wintry quarry
#

Actully the child object approach will also take that into account

#

both will

wintry quarry
#

do you mean y scale?

vernal sequoia
#

like y

#

yeah

wintry quarry
#

If you care about that then just multiply your ray distance by localScale.y

#

Why are you sending the rays from the top of the object though?

#

Why not from near the bottom?

#

Then the height of the object won't matter

vernal sequoia
#

In order to suddenly have my object a little underground.

#

it's the foundation. in my game

#

I kind of need to do 4 checks in the corners, and if they all pass it, then the object can be exposed)

sterile river
#

Hey guys, I have a problem with my third person movement. It won't really allow me to use W-A-S-D the way it should be and faces not the best directions 😄

#
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonMove : MonoBehaviour
{

    public Transform cam;
    
    CharacterController controller;

    Vector2 movement;

    float turnSmoothTime = .1f;
    float turnSmoothVelocity;

    public float moveSpeed;
    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;

        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg * cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);

        }
    }
}```
#

any idea what the problem is?

#

I use the cinemachine for the camera:

ivory bobcat
sterile river
#

Well, A key does the same as W and D the same as S

proud vigil
#

Ok im starting to Lose my Mind... can anyone explain that to me:
First Screen is My Project where he cant find the Callback to Override, Second Screen is the Documentation where it should CLEARLY exist...

sterile river
keen dew
#

The code looks needlessly complicated for that

sterile river
keen dew
#

yes

sterile river
#

Well, I got it from a tutorial 😅

#

There, the movement looks fine

wintry quarry
keen dew
#

It looks like it's meant for 2d movement

sterile river
#

Any other tutorial doesn't really help

proud vigil
#

@wintry quarrybasicly just he cant find that Methode to Override

sterile river
wintry quarry
proud vigil
#

Netcode for Gameobjects (both)

sterile river
wintry quarry
proud vigil
#

up to date and in the Project

vernal sequoia
#

Okay, thanks for the help, I'll try to come up with something else for this)

sterile river
swift sedge
proud vigil
proud vigil
#

@swift sedge can your sourcecode find those Callbacks?

wintry quarry
#

this is not netcode for gameobjects

#

Unet is ANCIENT

#

and deprecated

proud vigil
#

Omfg...

wintry quarry
#

you are using a unet tutorial

#

or documentation

sterile river
#

I tried so many scripts for third person movement but none really does the job I wanna have. Even the one from Brackeys 😄

prisma blaze
#

does anyone know a way to randomly spawn objects withtin a plane? this one i'm trying isn't good (i tried spawning 1000 objects)

proud vigil
#

thanks alot, gonna dig into that

sterile river
keen dew
swift sedge
keen dew
#
void Update()
{
    movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
    controller.Move(direction * moveSpeed * Time.deltaTime);
}
swift sedge
sterile river
# swift sedge have you used Input.GetAxisRaw?

yeah:

    {
        movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;

        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg * cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);

        }
    }```
ivory bobcat
#

Assuming top down

sterile river
sterile river
keen dew
#

No of course not

#

WASD movement doesn't rotate the player

ivory bobcat
#

You probably do not want to rotate and move with the same input..

#

Pick one behavior or the other for selected keys

keen dew
#

Again, the standard WASD movement is that the keyboard moves the player but doesn't rotate. Mouse rotates the player but doesn't move. And you said that's what you want.

sterile river
#

@keen dew @ivory bobcat that makes sense 😄 so i gotta have some code for the mouse that rotates the camera

ivory bobcat
#

If it's like WoW, you'd rotate with A and D and strafe with Q and E

sterile river
ivory bobcat
keen dew
#

mine is not tested, probably better to use something else

ivory bobcat
#

Mines isn't either UnityChanLOL

sterile river
#

hahaha 😄

ivory bobcat
#

Mobile discord coding without intellisense or looking up any API but the two logically should work for their specific use cases

sterile river
#
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonMove : MonoBehaviour
{

    public float speedH = 2.0f;
    public float speedV = 2.0f;

    private float yaw = 0.0f;
    private float pitch = 0.0f;

    public Transform cam;
    
    CharacterController controller;

    Vector2 movement;

    public float moveSpeed;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        Vector3 direction = new Vector3(movement.x, 0, movement.y).normalized;
        controller.Move(direction * moveSpeed * Time.deltaTime);

        yaw += speedH * Input.GetAxis("Mouse X");
        pitch -= speedV * Input.GetAxis("Mouse Y");

        transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
    }
}```
sterile river
#

w-a-s-d still doesn't feel right lol

keen dew
#

Follow a tutorial

sterile river
#

oooh i am 😄

keen dew
#

No you're not

#

half of that is the code I typed

sterile river
ivory bobcat
#

Define "feel right". I also suggest using a tutorial if you haven't implemented basic characters movement functionalities before.

sterile river
#

i don't know if something in the settings is wrong or in the code

ivory bobcat
keen dew
#

It doesn't take the player's current facing into account

#

follow a tutorial

deft yacht
sterile river
wintry quarry
deft yacht
#

my plugins folder had two folders the left one being the cause of my pain atm but it came with the game template, the right one being dotween

languid spire
deft yacht
#

sure sorry

languid spire
#

you've definitely got duplicate scripts there

deft yacht
#

hmmm, okay thanks, ill have to have a deep dive tomorrow, but for now ima get to bed aha, thats enough for one day. ill post an update, hope youre right

#

thanks a lot for the help!

prisma blaze
#

i caused an infinite loop, how do i get out of this?

wintry quarry
#

and do colliders = null

#

this will throw an exception

#

breaking you out of the loop

prisma blaze
#

that didn't work too

wintry quarry
#

you have to do it on line 57

prisma blaze
#

the problem is the function which has while() is also called a lot of times

wintry quarry
#

put the breakpoint on line 57

wintry quarry
#

show

prisma blaze
wintry quarry
#

this shows me even less

prisma blaze
#

"number" isn't a small number...

#

i forgot to change it before trying

wintry quarry
#

in the immediate window

#

and/or SpinningBoxScript.Type = null

prisma blaze
#

since while() is the one causing the loop

wintry quarry
#

with another breakpoint

wintry quarry
prisma blaze
#

thanks

#

nvm it didn't work

#

i kept trying the moving the yellow breakpoint arrow and it somehow worked, thanks

rich adder
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

inland socket
#

oh shit sorry

rich adder
prisma blaze
#
private bool IsCloseToAnotherBox(float x_dim, float z_dim)
    { var boxPosition = new Vector3(x_dim, 1, z_dim);
        var colliders = Physics.OverlapSphere(boxPosition,0.5f);
        foreach(var collider in colliders)
        {
            if(collider.gameObject.tag =="SpinningBox" || collider.gameObject.tag=="Player" || collider.gameObject.tag == "Wall")
            {
             return true;
            }
        }
        return false;
        }

is this the correct way to avoid objects overlapping? it works but i still get occational overlapping

#

like here

#

the box's scales are all 0.25, and the overlapping sphere is 0.5

#

so there should not be any overlapping right?

rich adder
inland socket
rich adder
inland socket
#

it's a bunch of little code blocks that culminate in a large one

#

i guess i'll just copy all those in?

rich adder
#

send the whole script thats throwing the error

#

only the line number is relevant

#

but need context for the whole script

prisma blaze
rich adder
#

you would see where exactly your overlap is and whatnot

prisma blaze
#

i'm not sure where to use this, do i put
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(transform.position, 1);
right under overlap sphere?

inland socket
#

getting this error:

Dialogue.QueueSpeech (System.String text, UnityEngine.Vector3 position) (at Assets/Scripts/Dialogue.cs:90)
Dialogue.Start () (at Assets/Scripts/Dialogue.cs:53)```

on this: https://hastebin.com/share/nisaxewuve.csharp
rich adder
prisma blaze
#

would this show me how the spheres would look like?

languid spire
#

yep, it's not initialized

rich adder
#

its static so unity doesn't new() and serialize it in the inspector, also because it doesn't serialize Queue type

inland socket
#

welp, 30 minutes wasted on that. thank you!

languid spire
trail creek
#

guys, why it pops the red thing under the text, it won't work:

rich adder
#

read what the underlines tell you

#

they're there for a reason

languid spire
#

i dont think he's seeing the red line two lines above the obvious ones

cosmic dagger
trail creek
rich adder
#

read what error says

short hazel
#

Code gets scanned top-to-bottom, always start with the topmost error

trail creek
# cosmic dagger What does the error say when you hover?

Severity Code Description Project File Row Deletion status
Error CS1061 'object' does not contain a definition of 'Interact' and no accessible 'Interact' extension method was found that takes a first argument of type 'object'. You're probably missing a using directive or assembly reference. Assembly-CSharp D:\Games\My project\Assets\Scripts\Player\PlayerInteract.cs 36 Active

cosmic dagger
polar acorn
#

Look at the errors in order

#

Top to bottom

rich adder
polar acorn
#

One error often causes future lines to error

trail creek
languid spire
#

no it's not

cosmic dagger
trail creek
rich adder
#

Intractable is probably not a static class

cosmic dagger
# trail creek

This pic is updated from the original. You've fixed the first error now . . .

trail creek
polar acorn
cosmic dagger
#

Now what does the next (topmost) error say?

trail creek
#

Severity Code Description Project File Row Deletion status
Error CS0120 An object reference is required for property, method, or non-static field 'Interactable.promptMessage' Assembly-CSharp D:\Games\My project\Assets\Scripts\Player\PlayerInteract.cs 35 Active

trail creek
cosmic dagger
trail creek
cosmic dagger
#

You're trying to access it from the class itself but the field is not static . . .

rich adder
#

@trail creek btw nice Gabibbo picture profile UnityChanLOL

rich adder
trail creek
short hazel
#

You're mixing up Interactable (the type), and interactable (the variable created one line above)

#

C# is case-sensitive

trail creek
#

ohhhh ok

#

one error down

#

there is the second one:

Severity Code Description Project File Row Deletion status
Error CS1061 'object' does not contain a definition of 'Interact' and no accessible 'Interact' extension method was found that takes a first argument of type 'object'. You're probably missing a using directive or assembly reference. Assembly-CSharp D:\Games\My project\Assets\Scripts\Player\PlayerInteract.cs 36 Active

line 36:

            if (inputManager.OnFoot.Interact.triggered)
short hazel
#

InputManager.OnFoot is an object it seems 🤔

dusk minnow
#

I need some help. Iam making a tower defense game in 3d and i have 2 towers with an example height of 1.5 and 3. I have some cubes with a given layer to place the towers at. Now i want the towers no matter of their height to be placed on top of the cube with its button exactly on top. So basicly the 1.5 high tower being .75 above the cube and the 3 high one 1.5 above. I hope my problem is understandable heres my code iam changing the system rn so some parts are confusing. https://paste.ofcode.org/3azFEDEqDX5zHY6FUT2d6vn

rich adder
#

yeah not entirely sure how Input System works, I assume OnFoot supposed to be the Input Action Map/

short hazel
#

The error resides in the InputManager class.

rich adder
#

Ahh had no idea there was such thing

trail creek
#

if you want i can send the InputManager.cs?

rich adder
#

yeah its naming issue

short hazel
rich adder
#

except this one gives missing definition

trail creek
rich adder
rich adder
#

oh wtf internal readonly object OnFoot;

rich adder
trail creek
#

The second video in the Lets Make a First Person Game series!
🖐In this video we are going to setup the foundations for our interaction system.

Come Join us on the Discord!
🎮 https://discord.gg/xgKpxhEyzZ

💚 Thanks for watching!

Helpful Links
https://dotnettutorials.net/lesson/template-method-design-pattern/

▶ Play video
short hazel
#

Yep line 12 is not supposed to be there

#

Ah I see what happened

#

They got the error, and used the IDE quick action "Create field in InputManager.cs" as it's what pops up first when you refer to an undefined member

#

Created it with type object since it can't know what type you'd like, and internal as it's the most restrictive, while still be able to access it from the outside

plucky tinsel
#

what does this new provide contacts option do ?

rich adder
#

oh yeah internal dead giveaway generated from IDE , good catch

trail creek
#

i deleted line 12, and now:

short hazel
#

So you need to use the one on line 8. Make it public and change its name so it's OnFoot

plucky tinsel
#

okay, thank you

trail creek
#

@short hazel i found this in the comments of the video:

Hey Everyone! I have only just realised there is some footage missing from the video!!!
You may encounter the error "'InputManager.onFoot' is inaccessible due to its protection level".
if you have this error you just need to change 1 line in the InputManager script.
Change this -> private PlayerInput.OnFootActions onFoot;
To this -> public PlayerInput.OnFootActions onFoot;

#

this is what you told me

#

ty

#

sorry for the ping

rich adder
short hazel
#

Yeah another trash tutorial lmao
At least it doesn't multiply mouse input with DeltaTime

trail creek
#

uhuhm

#

he does it

cosmic dagger
#

How do you skip (not put in) video from a tutorial?

short hazel
#

The Brackeys Effect™️

rich adder
#

im too self conscious

trail creek
#

btw it's working now

frozen mantle
rich adder
frozen mantle
#

So I had to move that code to start() instead

rich adder
#

ahh yes good ol script execution order

wanton hearth
#

Hello, Im following a tutorial on youtube to create a simple 3D game, when I press the action key "E", nothing happens, Im attaching a clip and the script in this thread. Could anyone please take a look and help a rookie out, thank you!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class doorCellOpen : MonoBehaviour
{
public float theDistance;
public GameObject actionDisplay;
public GameObject actionText;
public GameObject theDoor;
public AudioSource creakSound;

private void Update()
{
    theDistance = PlayerCasting.distanceFromTarget; //referring to playercasting script variable
}

private void OnMouseOver()
{
    if (theDistance <= 3)

    {
        actionDisplay.SetActive(true);
        actionText.SetActive(true);
    }
    //enabling the UI text
    if (Input.GetButtonDown("Action") && theDistance<=3) 
    {//button pressed, distance reduced = do the following
        this.GetComponent<BoxCollider>().enabled = false;//disable collision
        actionDisplay.SetActive(false);
        actionText.SetActive(false) ;
        theDoor.GetComponent<Animation>().Play("doorHingeAnim");//play anim
        creakSound.Play();//play audio

    }

}
void OnMouseExit()
{
    actionDisplay.SetActive(false);
    actionText.SetActive(false);
}

}

ivory bobcat
wanton hearth
ivory bobcat