#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 7 of 1

graceful spruce
#

ty i think that should work

wintry quarry
#

There should be typically not even be a copy of the prefab in the scene at edit time

languid spire
#

btw [SerializeField] does not make a variable accessible from another script

wintry quarry
#

I think he means he gets a reference to the script so he can access its data

summer stump
#

SerializeField makes it visible in the inspector

#

Ah

fossil drum
#
        Vector3 tgtMoveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;

This seems jank, even if you have 0.001 on vertical, the normalized makes it so the moveDir is always of length 1. So maybe that gives you the idea that it's throwing you in a random direction?

stoic spear
#

i also removed the normalise and the issue is still happening :(

#

so it seems to be zooming me in the opposite direction of the keys im pressing, and only when im mid-air

#

it just sometimes happens, sometimes it doesnt

fossil drum
# stoic spear im just using keys, so it is correctly 0,0,0 when it is meant to be

Well, it's hard to tell then, because I don't know which if and which else it goes into, and I also don't know all the parameters you have set.
Also you talk about zooming which I guess means it throws you in a different direction, and not something to do with camera zooming. Maybe a video/gif is handy to describe the problem.

stoic spear
#

yeah as in increasing my velocity and sending me flying away

vestal valve
#

Looks like I already did that.
Below is the code where I instantiated Boost(booster).
"ballpos" is the cube.
Now I need to use "On trigger" function on booster(Set to "Is Trigger" ON) but it must be triggered by ballpos(cube)
How to do that?
This script belongs to another gameobject(a gameobject I used just to keep the script alive, and the gameobject is "empty")

fossil drum
stoic spear
fossil drum
#

Your lateral velocity goes insane, which seems derived from your normal velocity.

fossil drum
# stoic spear

So add a debug.log for all the vectors in your AddForce methods.

stoic spear
#

oh i found the specific thing

#

so, its only on the Z axis, if i start a jump going right, then press the left button, it zooms me

#

so if i try to change my direction midair

#

ive removed the multiplier and its still an issue

fossil drum
#
        if (rbLateralVelocity.magnitude > tgtSpeed) rb.AddRelativeForce(-tgtMoveDir * (rbLateralVelocity.magnitude - tgtSpeed + addSpeed * multiplier), ForceMode.Force);

Also, this is weird, if your magnitude is high, you add more force. Maybe comment out that line.

stoic spear
#

yeah, yeah

#

i did that and added the inverse of that if statement to the else above it

#

seems to be working fine now

#

i am just a little silly

final kestrel
#

https://hatebin.com/lamunjbvmq hey everyone. This is my script. The issue I have is that my character goes up and down in a straight line when I jump. It does not seem like a real jump If i make myself clear. How can I achieve that realistic jump look?

dark laurel
#

oh, wait, you're not doing it that way, uhm, standby

#

Oh, and I misunderstood - you're not talking about horizontal movement issues, you're talking about linear up/down - ie, gravity not being applied.

Your issue is that you're just adding "gravity times time" to your y position. You're already using a collider so if your level is all setup with rigidbodies, just enable gravity on your player object and change the bit of code in jump() from trying to do gravity yourself to just applying a one time upward force

rotund bronze
wintry quarry
final kestrel
rotund bronze
#

ah will try thx

final kestrel
#

I thought character controller and rigidbody didnt go well together

wintry quarry
# rotund bronze ah will try thx

e.g.

Plane p = new Plane(Vector3.up, Vector3.zero);
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
p.Raycast(r, out float enter);
Vector3 worldPoint = r.GetPoint(enter);
Vector3 cellCoordinate = tilemap.WorldToCell(worldPoint);
Vector3 cellCenterWorld = tilemap.GetCellCenterWorld(cellCoordinate);```
rich adder
#

isn't that wat a jump iss?

dark laurel
# final kestrel I thought character controller and rigidbody didnt go well together

you're right.. I don't quite see at a glance what's wrong with your script though, but it's a little confusing.. like why are you setting the y velocity to -2 when the player is grounded? why are you multiplying a bunch of constants when the player jumps? why are you multiplying y times delta time and then again setting velocity times deltatime in Move()?

final kestrel
#

Setting the velocity to -2 just so there is still gravity when its grounded. I thought I should multiply the gravity in jump method to have them applied? So I could fall down I think

final kestrel
dark laurel
#

i'd also make sure your IsGrounded() is actually retruning false while the player is in the air, since you are checking to see if the Y velocity is < 0 (then setting it to -2??)

#

if your isgrounded is returning true then your player is going to "float" down at y velocity = -2 no matter what

final kestrel
#

Can I post the video in this channel?

rich adder
#

yes

final kestrel
#

I dont double jump or anything

rich adder
final kestrel
#

It does not feel like im jumping its just im going up and down.

wintry quarry
rich adder
#

probably that much gravity doesn't help either

final kestrel
#

can I send another video?

rich adder
#

sure

final kestrel
#

I played with the gravity settings some

tawdry rock
# final kestrel

Fine to me as well. Also a cool trick if you using a cube when jumping you can rotate it in a Z or X axis depending which direction the cube faceing. So when you jump it also do a little "flip". A nice touch but adds more to the jumping vibe! ๐Ÿ˜„

late burrow
#

how i alter this to give exact same results for each player
if (Physics.Raycast(allparticles[i].position, allparticles[i].velocity, out hit, allparticles[i].velocity.magnitude * Time.deltaTime, 1 << 0))

unique gust
#

hey guys i have a project a platform game and i need to know how can i set a game over when the player jumps into the void can someone help me

#

i already made a box collider 2d outside of the camera

final kestrel
# final kestrel

Does not it feel a little like not jumping but just moving upwards or am i tripping

#

It was fine to me as well but a friend said so and im not sure anymore ๐Ÿ˜„

tawdry rock
unique gust
tawdry rock
unique gust
#

I already make it and make the if for the the ontriggerenter

#

I just don't know how to continue

tawdry rock
# unique gust I make a separeted script for the game over ui?

Make a UI first then hide it.
On the player inside the update method write:

if (transform.position.y < -20)
        {
            Debug.Log("Game Over: Player went off the screen.");
            playerAlive = false;
            gameOver();
        }

make sure to have a bool playerAlive = true; then have a gameover method that will trigger the gameover ui with ex. gameOverScreen.SetActive(true);

jagged gulch
#

Working on a simple weapon recoil system from my gun. Ive followed tutorials for weapon recoil and tried a bunch of different ideas, but most seem to implement a system that just rotates the camera up and then back to the origianl position. Im more lookin for a way to just bump the camera up by a rotation so the player has to reset the camera. Ive been goin over this since yesterday afternoon to no avail unfortunately.

    private Vector3 targetRot;

    [SerializeField]
    private float recoilX;
    [SerializeField]
    private float recoilY;
    [SerializeField]
    private float recoilZ;

    [SerializeField]
    private float snappiness;
    [SerializeField]
    private float returnSpeed;

    void Start()
    {
        
    }

    void Update()
    {
        targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
        currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
        transform.localRotation = Quaternion.Euler(currentRot);
    }

    public void RecoilFire()
    {
        targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
    }```
with the current looking result lookin like this:
#

(this has easily been the hardest part of the project so far notlikethis , I can't wrap my head around what to do here)

unique gust
sullen rock
#

this is probably a dumb question, but here I go.... when I make an abstract class - lets call it "customEvent"
and then make multiple classes that inherit from it - "customEvent1", 2 and so on
can I put those classes into a collection of some sort, so I can loop through them efficiently?

languid spire
#

yes, make a collection of the abstract class then anything which inherits from it can be placed inside

sullen rock
#

So just like a List<customEvent>

#

?

languid spire
#

yes

sullen rock
#

And is this a dumb implementation or an actually decent practice?

languid spire
#

normal practice

wintry quarry
languid spire
#

lol

sullen rock
#

Nah, it was just an example haha

wintry quarry
#

A typical example would be like:

abstract class Fruit {}
class Apple : Fruit {}
class Banana : Fruit {}

List<Fruit> fruits = new();
fruits.Add(new Apple());
fruits.Add(new Apple());
fruits.Add(new Banana());```
languid spire
valid finch
#

I feel like I am missing something.
within the update I have a method.
within that method there are if statements..
when the if statement isn't true anymore the method is still running within the update.. I don't know what I'm not seeing.

wintry quarry
#

the stuff inside the if will not run whent he condition is false

#

if the method is running unconditionally, it will always run

#

if only controls stuff inside its brackets

sullen rock
valid finch
# wintry quarry if the method is running unconditionally, it will always run
public void FootballFollow()
{
    if (!football.activeSelf && footballFollowing.activeSelf)
     {

         football.transform.position = following.transform.position;
         Debug.Log("Follow");
     }
    

      
    if (!football.activeSelf && !footballFollowing.activeSelf) 
    {
        football.SetActive(true);
        var stopFollow = following.transform.position;
        stopFollow.x += -3;
        football.transform.position = stopFollow;
        Debug.Log("Dont follow");
    }

    else
    {
        return;
    }

is anything in here wrong?

wintry quarry
valid finch
#

When they are both false.. the second if doesnt run

#

the first one keeps running

wintry quarry
#

I assume that your assumptions about what is true and what is false are incorrect

#

use Debug.Log to check

polar acorn
wintry quarry
#

e.g.

Debug.Log($"football active: {football.activeSelf}, footballFollowing active: {footballFollowing.activeSelf}");```
#

(put this as the first line in the function)

polar acorn
#

Also turn off collapse so you can actually see the order the messages are coming

valid finch
#

I will use that. I am just confused.. because in the scene view as they are disabled and enabled

#

it lines up with what I want.. but when they are both disabled.. the states don't reflect that

#

even though within the scene they are clearly disabled

sullen rock
#

The issue is, I kinda need to be able to serialize the list and be able to edit the variables of each of the inheriting classes outside of playmode, which makes me feel like this is a dumb approach

wintry quarry
wintry quarry
valid finch
#

wow.. didn't even know that was a thing

wintry quarry
#

you could do it with Odin inspector

polar acorn
valid finch
#

top left

#

they are both disabled

polar acorn
tawdry rock
#

is the Character Controller has it own collider? If i put it on my player i cant got through walls but if i put it on a npc, they can go through walls.

polar acorn
valid finch
polar acorn
tawdry rock
polar acorn
tawdry rock
#

transform.position += transform.forward * moveSpeed * Time.deltaTime;

polar acorn
#

you're teleporting

#

that's not going to respect any collisions

valid finch
tawdry rock
polar acorn
#

but teleporting nonetheless

sullen rock
# wintry quarry unity serialization doesn't generally support polymorphism, especially not in th...

My use case is - I have X amount of possible events that could happen (eg. Lights go out) and I need to trigger them randomly - could I, in theory, define abstract class of the event, make a class that inherits from it for each and serialize them outside of a list, just as separate variables and then have the "current event" variable set as the original abstract class type, so I can store any of the events that inherit from it inside?

#

Does that make any sense at all or am I out of the loop completely?

valid finch
#

So even though the script is still checked on the right in the inspector, the stuff isn't running because the object is disabled?

polar acorn
#

Basically, disabling a thing always disables all the stuff under it automatically

valid finch
#

Ok, the fact I saw the other stuff still checked.. I didn't understand that

wintry quarry
valid finch
#

Thank you

wintry quarry
#

and then just have a List<SpookyEvent>

#

and pick a random one from there?

#

then you can determine the actual behavior with a switch or a Dictionary keyed on the enum to a delegate

tawdry rock
polar acorn
polar acorn
wintry quarry
#

such as with the CC

sullen rock
#

these events will have the player do something, thats why I though an enum wouldnt be enough

like, when lights flicker, you need to turn the switch off and on
they are also kinda all over the place - the event could be related to lights, sounds, objects and so on

wintry quarry
#

you can separate that behavior from the choosing and representation of those events

#

especially if you want to represent it in the inspector for examplke

#

though I guess maybe you want parameters for all these things

tawdry rock
#

Alrighty, i will look into it. thanks for the info.

valid finch
sullen rock
#

you are right that I am probably overcomplicating, Im trying to find a balance between maintainability and modularity

safe radish
#
Debug.Log(parentTransform.gameObject.name);
        stats = parentTransform.GetComponent<Stats>();
        if (stats == null)
            Debug.LogError("Stats component not found on parent.");```  im trying to reach my stats script on the player gameobject from my charactercustomizer script but am getting null
polar acorn
safe radish
valid finch
safe radish
pearl lodge
#

Does anyone know why this error is happening?

modest palm
#

iโ€™m getting a directory not found exception when trying to build

valid finch
sullen rock
#

@wintry quarry I think the easiest solution for me will be a single event template class with a unityevent to handle the different logic of each of the events

queen adder
#

Is there something that could cause Trail material input missing from the particle system after enabling trails?

#

generally my particle system doesnt show up trail material input under renderer component after enabling Trails component

valid finch
#
var ballRandomLocation = new Vector3(Random.Range(-10.0f, 10.0f), 0, Random.Range(-10.0f, 10.0f));

So would I be able to use this in

stopFollow.x += ballRandomLocation;
queen adder
#

What could be causing it to be missing?

valid finch
queen adder
#

its usually under renderer right under Material

#

its not popping out and editor is not throwing any errors aswell

valid finch
#

Is the public class missing?

queen adder
valid finch
#

Look in your code near the top of one of them that works. and compare it to the one that doesn't

queen adder
short hazel
#

You're asking in a code channel, expect code anwsers

queen adder
solar tide
#

This code works completely fine. But someone told me that Quaternion Euler is too expensive or not to be used. Is this true? And if so, how do I change this code to make it less expensive?

queen adder
#

I though i was in unity talk , sorry

valid finch
#
{
   football.SetActive(true);
Vector3 stopFollow = following.transform.position;
Vector3 ballRandomLocation = new Vector3(Random.Range(-2.0f, 2.0f), Random.Range(-2.0f, 2.0f), 0);
stopFollow.x = ballRandomLocation.x; // Assign the x-coordinate of ballRandomLocation to stopFollow.x
football.transform.position = stopFollow;
Debug.Log("Don't follow");
}

Any ideas?

#

cuz I don't believe it needs to be instantiating.. so the documentation on it isn't making sense

short hazel
#

I don't know what you want to do, so hard to answer

#

System.InvalidOperationException: Cannot read minds through HTTP

valid finch
#

haha

#

Sorry. Trying to use ballRandomLocation to choose a random location for the football.transform.position

short hazel
#

football.transform.position = ballRandomLocation;

valid finch
#

This actually is working now

#

since I updated it

#

I need to add the stopFollow.y = too

short hazel
#

That's the long version but it works as well

valid finch
# short hazel That's the long version but it works as well
{
    football.SetActive(true);
    Vector3 stopFollow = following.transform.position;
    Vector3 ballRandomLocation = new Vector3(Random.Range(-2.0f, 2.0f), Random.Range(-2.0f, 2.0f), 0);
    stopFollow.x = ballRandomLocation.x; // Assign the x-coordinate of ballRandomLocation to stopFollow.x
    stopFollow.y = ballRandomLocation.y; // Assign the y-coordinate of ballRandomLocation to stopFollow.y
    football.transform.position = stopFollow;
    Debug.Log("Don't follow");
}

feels longer than it needs to be. I think you are right

#

hmm maybe not though

#

cuz I need the follow.
and the football.

short hazel
#
  1. You don't need to store the position in the stopFollow local variable
  2. Yes you can assign the whole vector directly
queen adder
#

Quick note on the issue i had, if anyone happens to have it in future, even though my editor didnt throw any error or warning, it was indeed bugged out and restarting editor fixed it ๐Ÿ‘

valid finch
valid finch
queen adder
short hazel
#

At this scale no, even in Update

#

Worry more about calls to Find() and GetComponent<T>() in Update

valid finch
#

Alright. But for future reference it's always best to correct things like this before it becomes a habit

queen adder
#

it can hurt performance on low end devices dont be fooled, anything in update can get heavy, so it depends for what platform you are building for, if its for PC then its minimum impact

short hazel
#

Copying a value type around is not

queen adder
#

Good practice is to use update only when u must and for inputs

#

Usually if you want to have code repeat u use Coroutines instead , performance wise they are great

jagged gulch
#

Im just lookin for a way to bump the camera up when firing and then clamp the camera rotation at a certain point once it hits that in the recoil

#

any suggestions?

pearl lodge
rare basin
#

if i start a coroutine, then disable the game object, does the coroutine still run?

narrow badge
#

hey sorry

#

hru guys

#

can any one help me

rare basin
#

don't ask to ask

slender nymph
rare basin
#

that's a shame

#

i'll disable the sprite and collider then

#

i want my object to disappear and respawn after 2 seconds in different location

#

so wanted to start respawn coroutine, disble object

#

and hoped that it will re-enable inside that coroutine

slender nymph
#

if you call StartCoroutine on another object you could do that, it's just that a coroutine instance that is owned by a monobehaviour that is disabled will be disabled as well

rare basin
#

well i dont really have where to call that

#

i have Square.cs and HealthSystem.cs

#

health system has TakeDamage() and when the dmg drops <= 0 i call RespawnSquare() function from Square.cs

#
    public void RespawnSquare(float delay)
    {
        StartCoroutine(RespawnCoroutine(delay));
    }

    private IEnumerator RespawnCoroutine(float delay)
    {
        yield return new WaitForSeconds(delay);

        SetSquareRandomPosition();
    }
#
    public void TakeDamage(int damage)
    {
        if (isDead) return;

        currentHealth -= damage;

        if(currentHealth <= 0)
        {
            isDead = true;
            owner.RespawnSquare(LevelDataStorageManager.Instance.currentLevelData.respawnDelay);
        }
    }
#

Collider is on Square Object, and SpriteRenderer is under Graphics

#

i just hoped that i can somehow disable the root object

#

I probably could have some sort of "RespawnManager"

#

who will call the coroutines

#

but idk if its a good idea

pearl lodge
#

Does anyone know who to fix this? it seems I can no longer make references to some libries like TMPro

slender nymph
#

just vs code things lmao

#

you could try regenerating project files. or you could consider switching to visual studio which is far less likely to randomly break

queen adder
#

but yeah you should also use visual studio to avoid most of issues u can come across with vscode , plenty ppl here only asking how to fix this and that on vscode

rare basin
#

I want to spawn a prefab in a random (visible) position. How can I get the "visible" area and spawn inside that area with some margin? so it doesn't spawn at the edge and half of the object is off camera etc

queen adder
rare basin
#

I was also thinking at creating a box collider 2D and spawning inside that box collider

#

but idk if its good idea

queen adder
rare basin
#

yea

#

ty

pearl lodge
#

Then back in Unity installed this package.

#

All is working well now.

slender nymph
#

yeah that's how you're meant to configure vs code now that microsoft has taken over maintaining the unity extension

pearl lodge
#

I just don't know why is has to have visual studio editor installed when I use visual studio code?

slender nymph
#

because that is what creates the working project files for vs code now

#

you can uninstall the vs code editor package

pearl lodge
slender nymph
#

huh?

#

i'm talking about uninstalling the Visual Studio Code Editor package. the unity extension requires the Visual Studio Editor package now

#

literally the one right above the one you have selected in your screenshot can be removed

ashen ferry
#

if I want to make a setting changing font of all text elements in my game what do I do

pearl lodge
slender nymph
#

yes. the vs code editor package is no longer required because as you have already discovered, the unity extension in vs code now uses the visual studio editor package

pearl lodge
rare basin
#
    public void SetSquareRandomFreePosition()
    {
        //Dangerous loop, yet I don't have other idea for now
        while (true) 
        {
            var randomPos = GetRandomVisiblePosition();

            Collider2D[] squaresNear = Physics2D.OverlapCircleAll(randomPos, squareSize);

            if (squaresNear.Length == 0)
            {
                transform.position = randomPos;
                break;
            }
        }
    }

I am spawning a Square in a random position inside the Camera, then I am doing a check if there are no other Squares near the possible spawn position, so I am only spawning the squares in free positions, althought it doesn't work and squares spawn on top of each other, why?

unkempt locust
#

help me please

#

I'm trying to make a slide, but when I click the C key, the player scales down, but it doesn't go forward with the rigidbody, can you help me with this?

ivory bobcat
unkempt locust
unkempt locust
unkempt locust
ivory bobcat
unkempt locust
#

I want to do the following, I want the player to scale down, and be propelled forward

ivory bobcat
#

Does it work without scaling?

#

If it doesn't work without the scaling, it won't work with it.

unkempt locust
#

I don't know about the rigidbody, but the slide doesn't work without reducing the player's scale

ivory bobcat
#

Comment out the scaling and see if the player propels forward

unkempt locust
#

ok

rare basin
unkempt locust
ivory bobcat
#

So fix that first.

wary sable
#

does anyone here have much experience with the kiwicoder free behavior tree?
I'm attempting to add my own nodes but am having trouble assigning gameobjects and other classes as NodeProperties...
(for example adding a target object for a moveTo node keeps yielding a "Type mismatch" error when putting in a G.O with the valid type / class)

Ive even tried to circumvent it by searching for the target object using GameObject.find and pulling data from there but it just spits out the property anytime I attempt to use it.

unkempt locust
ivory bobcat
#

Maybe the if statement is never true or maybe the coroutine is never started

unkempt locust
#

this is my rigidbody of my player

eternal needle
unkempt locust
#

yes, it is being started, because the player's scale changes but it is not propelled forward

short hazel
#

Kinematic rigidbodies do not react to AddForce()!

rare basin
ivory bobcat
short hazel
#

You activated it, compared to your prefab

#

"Is Kinematic" is in bold, showing that it's overriden compared to the prefab

rare basin
#

@eternal needle why are you reacting

#

OverlapCircle2D is just a method that gets all coliliders inside the sphere

unkempt locust
rare basin
#

doesnt matter if i have BoxCollider2D lmao

eternal needle
short hazel
#

Yes

unkempt locust
#

how I can fix?

short hazel
#

Disable kinematic

rare basin
short hazel
#

And it will react to forces fine

unkempt locust
short hazel
#

Then you have code applying force elsewhere

eternal needle
rare basin
#

you suggested that OverlapCircle2D wont detect "boxes"

eternal needle
#

alright ill pull out the paint drawing..

pearl lodge
rare basin
unkempt locust
# short hazel No?

So, I just disabled "Is kinematic" and it worked!, but my player is going down ramble

rare basin
#

i understand what do you mean @eternal needle but even when putting hilarious big radius number like 10

#

it still doesnt detect

unkempt locust
#

I'm using Unity's Standard Assets

polar acorn
rare basin
#

i understand i dont need them to match

#

i want bigger overlap than my square

rare basin
#

my square size is 1 units, i want to do overlap circle with 2 units from square center

#

even if i put like 100 radius it still spawns on top of each other

short hazel
#

Look at the code

#

See where you add forces

eternal needle
rare basin
polar acorn
pearl lodge
#

maybe add this to your box script

    private void OnDrawGizmos() 
    {
        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(transform.position, squareSize);
    }

to see the cricles

unkempt locust
queen adder
#

hey guys I'm new to unity and i need some help. so the thing is I'm working on a prototype based on marvel snap and i need to make it work multiplayer as well as playable with AI. for this case I'm using 4 lists

  1. Player Owned Cards
  2. Used Cards (Player)
  3. Enemy Owned Cards
  4. Used Cards (Enemy)

is there any way i can use the lists outside the class by using interface which behaves as an AI as well as the player

rare basin
#

they are colliders, not set to is trigger @polar acorn

short hazel
unkempt locust
#

When I disable "Is kinematic" unity debugs an error for me, this is the error @short hazel

rare basin
#

so it clearly shows correctly :/

eternal needle
rare basin
#

let me share some more code I have SquareSpawnManager with functions:

    private void Start()
    {
        Camera.main.orthographicSize = LevelDataStorageManager.Instance.currentLevelData.cameraSize;
        SpawnInitialSquares();
    }

    private void SpawnInitialSquares()
    {
        remainingSquares = new List<Square>();

        for(int i=0; i< LevelDataStorageManager.Instance.currentLevelData.squareCount; i++)
        {
            Square square = Instantiate(squarePrefab);
            remainingSquares.Add(square);
            square.SetSquareRandomFreePosition();
        }
    }
#

and Square

    public void SetSquareRandomFreePosition()
    {
        //Dangerous loop, yet I don't have other idea for now
        while (true) 
        {
            var randomPos = GetRandomVisiblePosition();

            Collider2D[] squaresNear = Physics2D.OverlapCircleAll(randomPos, squareSize);

            if (squaresNear.Length == 0)
            {
                transform.position = randomPos;
                break;
            }
        }
    }
unkempt locust
#

@short hazel

rare basin
short hazel
#

No need to ping every 15 seconds

polar acorn
# rare basin

Add this log after your overlap:

Debug.Log($"{gameObject.name} is checking a circle of radius {squareSize} around {randomPos} and found {squaresNear.Length} collisions.");
pearl lodge
#

Does your circle have a collider?

rare basin
unkempt locust
polar acorn
short hazel
# short hazel No need to ping every 15 seconds

Looks like your weapon model has an issue, the mesh collider on it is not convex, but it should be, as per the error
Standard Assets is deprecated, it has been replaced with the newer Starter Assets

rare basin
#

they stack a lot ๐Ÿ˜„

short hazel
#

And just fix the error

#

What's up with these half replies

unkempt locust
short hazel
#

Dude

polar acorn
rare basin
#

sure

short hazel
#

There's literally a check box that says "Convex" on your mesh collider, you need to check it

unkempt locust
rare basin
#

these squares

#

square 1

rare basin
#

sorry, wrong inspector

#

this is the main object, Square 1

#

this is square 2

unkempt locust
rare basin
#

is there a problem with spawning the Squares in a for loop? maybe they aren't processed yet or something, i dont know i feel lost

#
    private void SpawnInitialSquares()
    {
        remainingSquares = new List<Square>();

        for(int i=0; i< LevelDataStorageManager.Instance.currentLevelData.squareCount; i++)
        {
            Square square = Instantiate(squarePrefab);
            remainingSquares.Add(square);
            square.SetSquareRandomFreePosition();
        }
    }
polar acorn
# rare basin

I think what might be happening here is that they all check their locations at once, and no one is around yet. Then they all confirm their destinations are okay, then all teleport there together.

rare basin
#

so it should do one iteration

#

then another one etc

short hazel
polar acorn
#

I'm not sure how to fix, but I'm thinking

#

At least trying to think of a way to see if this is happening

rare basin
#

public void SetSquareRandomFreePosition() make this a bool

#

and coroutine

#

and WaitUntill?

#

in the spawn loop ?

rare basin
polar acorn
rare basin
#

let me try

unkempt locust
rare basin
#
    private IEnumerator SpawnInitialSquares()
    {
        remainingSquares = new List<Square>();

        for(int i=0; i< LevelDataStorageManager.Instance.currentLevelData.squareCount; i++)
        {
            Square square = Instantiate(squarePrefab);
            remainingSquares.Add(square);
            yield return new WaitUntil(() => square.SetSquareRandomFreePosition());
        }
    }
#

let's see

short hazel
rare basin
#

well, i can defo see the progress but they are still overlapping (not as much as before tho and not that often)

eternal needle
rare basin
#

i did another yield wait for fixed update

eternal needle
#

the list of objects already spawned

rare basin
#

ow

short hazel
# unkempt locust here?

Ah, that's an issue I see here. You cannot have a Character Controller and a Rigidbody or Collider on the same object, they will conflict with each other

rare basin
#

and do Vector2.Distance?

#

yea i might try that

#

sounds better than my idea

unkempt locust
rare basin
#

i already have a list of spawned squares

#

so i can just read their position

#

and do a distance check

eternal needle
#

if you want it radius based then yea that could work. you could use sqr magnitude instead and just compare it to the (squaresize * squaresize) so you save yourself a sqrt call

rare basin
#

it would be heavy for performance

short hazel
rare basin
#

because i have levels with 500, 600, 700 squares

#

so if im spawning square number 400, i have to loop through all previous squares

#

and compare distance

#

and if none is near then spawn

unkempt locust
eternal needle
# rare basin and if none is near then spawn

i cant imagine spawning 700 squares and doing 700 overlap functions would be much better. still this is a large amount of objects, its not gonna be instant unless you remove the randomness part and spawn them differently

short hazel
unkempt locust
#

without the rigidbody, the slide doesn't work, and without the controller character the player doesn't work

rare basin
#

but then i have 700 squares with distance checks

#

and spawning square 699 i have to do forlopp for 698 already spawned squared

#

and next iteration spawning square 700 i have to do forloop for 699 already spawned

#

etc

short hazel
#

Research

#

Google, bing, whatever your usual search engine is

unkempt locust
short hazel
#

Well, an alternative would be to remove the rigidbody, collider, character controller, first person controller from the object, and adding the first person controller again

#

If it's well made, it'll add the required components by itself

tall nest
#

Guys Microsoft Visual Studio is so crashing, should I use another IDE like Visual Studio Code? or keep the purple one

pearl lodge
rare basin
#

shouldn't really matter

#

why

rare basin
#

it's just setting the position

#

doesnt matter if i add it before or after

tall nest
rich adder
valid finch
#

just a quick example for context. On the bottom the ball would be bouncing along only the x axis. But since this is simulated 3d space.. the example on the top is more of what it would look like. Has anyone ever attempted this. Wondering about trying to get gravity to work in this way. If not using gravity, I think just keeping a hitbox where the red circle is and faking depth using animations is the way to go.

does this belong here(or in #๐Ÿƒโ”ƒanimation)

rich adder
tall nest
#

because the purple one gets 2GB ram

#

which is the half of my RAM

#

ok thanks for helping, bye

rich adder
short hazel
#

Poor computer, has 4gb RAM and Windows requires at least 2 by itself to work properly

rich adder
#

Time to throw good ol windows XP on that ish

slender nymph
#

man i've been struggling with 16gb recently. i can't imagine going back to 4 ๐Ÿ˜ฑ

valid finch
#

What would you call the thing I'm trying to do.. just so I know what to research? moving an object in 2d space simulating 3d? Just don't know I should word it

slender nymph
#

can you elaborate on what that means?

slender nymph
#

I think just keeping a hitbox where the red circle is and faking depth using animations is the way to go.
yeah that would probably be the way to go

#

unless of course you want to actually use 3d objects and physics

valid finch
#

Yeah, I am not using 3d objects.

#

I will use physics I think for the balls momentum

slender nymph
#

the "and physics" was also in reference to "3d"

#

i feel like this isn't really a code question anymore

valid finch
#

Good point. Thank you for your help

pine edge
#

Hey guys, I was wondering how I could tie two values to each other? Trying to tie a mesh's colour to a value but unsure how to do it. here's a code snippet: ```CS
// time (s) to reach peak value currently = 5
ballMesh.material.color = Color.Lerp(ballMesh.material.color, Color.red, time);
// colour needs to be peak (ie fully red) at x seconds. x = 5 in this case

polar acorn
pine edge
#

I tried that but it doesn't work. it never reaches max "redness". There's also an inverse function that lerps back from red to a default colour, but by doing time/x also stops it from returning to default

cosmic dagger
#

once the time reaches the duration, you manually set the value at the end . . .

pine edge
#

but I could do that without using lerp, it would just be an instant colour change

#

when I say it doesn't reach max colour, i mean it's quite off

#

not buy say 10 in the red channel

jagged gulch
#

Hey guys, Ive been stumped really bad with this recoil system Ive been trying to implement. Ive been at this for two days scouring the web, but to no avail. Im trying to add in a basic weapon recoil system that gets recoils up when a gun is fired, but have not been able to find a guide or suggestions on how to do it. Most guides are for fully automatic weapons that reset the camera after firing is complete (which is not what Im lookin for). #๐Ÿ’ปโ”ƒcode-beginner message any suggestions?

pine edge
#

so you want a system that recoils up, but leaves it to the user to recentre?

jagged gulch
#

exactly

#

notlikethis youd think this would be easy to find

pine edge
#

can't you just follow the guide and just ignore the recentring code?

jagged gulch
#

Ive tried that

short hazel
#

I pretty much have the same code on my end for recoil, and it works
You sure there's no other scripts that set the rotation directly, and could override what the recoil script does?

jagged gulch
#

so Im trying to figure out how to clamp it at a certain rotation

short hazel
#

The clamping would be done before you add the recoil to the vector

jagged gulch
# short hazel The clamping would be done before you add the recoil to the vector
    {
        targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
        currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
        transform.localRotation = Quaternion.Euler(currentRot);
    }

    public void RecoilFire()
    {
        targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
    }``` so in my current implementation, would I clamp the targetRot in RecoilFire() or in update? or clamp currentRot?
wary sable
#

Hey, im trying to work with the kiwicoder behavior tree, and im running into an issue where it wont accept public / serialized properties from the inspector. I dont know if anyone can provide some advise or if I'm just going to have to pony up for a real BT asset.
The issue is a little tough to but into writing but in short, its just like making a public or serialized property in a normal script, where it appears in the inspector and you can select an object of a specific type from the field. Except when you select an object from that field it errors out and says that there is a type mismatch, when you literally can't select an object of the wrong type

heres a video of it as well
https://cdn.discordapp.com/attachments/1146187317502029917/1154870484362612736/20230922-2002-19.6366722.mp4
ignore the poor naming, I did this in a different project to double check it wasnt a bug caused by a bad library

short hazel
#

But you can do it on multiple lines if you want

#
targetRot = new Vector3(
  Mathf.Clamp(targetRot.x - recoilX, min, max),
  targetRot.y + Random.Range(-ry, ry),
  targetRot.z + Random.Range(-rz, rz)
);

Since the new vector is not added with += make sure to do the addition in the individual vector components

proper mesa
#

Iโ€™m new to unity and i am wondering about how i can refference a float from one script in another script.

jagged gulch
slender nymph
jagged gulch
#

so I tried ```void Update()
{
//targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
transform.localRotation = Quaternion.Euler(currentRot);
}

public void RecoilFire()
{
    targetRot = new Vector3(
            Mathf.Clamp(targetRot.x - recoilX, 20, 80),
            targetRot.y + Random.Range(-recoilY, recoilY),
            targetRot.z + Random.Range(-recoilZ, recoilZ)
            );
    //targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
}```
#

and used 20 and 80 as a min and max example

#

since my current clamp on my player script is 80

#

camera gets a bit wonky unfortuneately notlikethis

short hazel
#

Might want to use 0 (or less) as the lower bound to Clamp. Here it says that the X rotation should be no less than 20 degrees which is not right. The default local rotation (pointing local forwards) is rotation X = 0

slender nymph
jagged gulch
slender nymph
#

are you sure the guide was using Update and not FixedUpdate?

short hazel
#

I recognize the variable names, procedural aiming system video right?

short hazel
#

I used that too but saw the discrepancy and put it all in FixedUpdate

#

With FixedDeltaTime eveywhere

#

Looks like it's applying horizontal recoil fine

#

And rotational (around Z) too

slender nymph
#

wouldn't even need to change the deltaTime to fixedDeltaTime if everything is moved to FixedUpdate since it returns the value of fixedDeltaTime when called from FixedUpdate

timber tide
#

your camera is rolling along with the directional shift

jagged gulch
#

not sure why notlikethis

short hazel
#

Yeah it's normal, it adds a nice touch when used slightly, need to keep the values low

#

not sure why
Well you apply random Z rotation in the ApplyRecoil method

jagged gulch
#

(my current setup just for reference)

#

Im still stumped tbh

short hazel
#

Actually when you need to rotate up, you subtract the X rotation, which means your clamp should be in the negative range, like (v, -90, 0)

#

I never remember, but in the Inspector, to look up, you input a negative X rotation right?

jagged gulch
sonic sphinx
#

Pardon all, I have a quick beginner question:

I have a tile-based 2D game with parallax backgrounds. When I do an orthographic zoom out, everything gets smaller (as expected!)

However, I want the far background to remain the same. Is there a way to exempt any individual layer from the zoom? Or do I need to write a script that scales the background up when zooming out?

modest dust
#

Not sure but I suppose you could have it on a canvas

#

Have it set to screen space overlay

#

It shouldn't be affected by zoom

sonic sphinx
#

Thank you! I'll investigate and see if that works.

rare basin
#
    private void Update()
    {
        transform.Translate(transform.up * moveSpeed * Time.deltaTime);
    }

how do i move object up but in it's local space?

jagged gulch
#

iirc

short hazel
#

Translate operates on local space by default - use Vector3.up

cosmic dagger
rare basin
#

ow now i see second paraemeters

#

WorldSpace.Self etc

short hazel
#

For completness, you can pass a second argument to Translate specifying which space to apply this in

#

Default is local

rare basin
#

yea just noticed

#

thank you

shell sleet
#

Is disabling the Unity splash screen in Personal version currently available in the most recent version?

short hazel
short hazel
jagged gulch
short hazel
#

Well actually no

#

You swapped the two operands of the subtraction

#

It should be target.x - recoilX

#

target.x + (-recoilX) for easier visualization, like the other args

jagged gulch
short hazel
#

Can you post the full updated code?

jagged gulch
#

yeah np

#
void FixedUpdate()
    {
        //targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
        currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
        transform.localRotation = Quaternion.Euler(currentRot);
    }

    public void RecoilFire()
    {
        targetRot = new Vector3(
                targetRot.x - recoilX,
                targetRot.y + Random.Range(-recoilY, recoilY),
                targetRot.z + Random.Range(-recoilZ, recoilZ)
                );
        //targetRot += new Vector3(-recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
    }```
#

currently looks like this when playin

short hazel
#

Looks normal to me

#

It's not returning back to the zero rotation cause the first lerp is commented out, but otherwise I don't see issues here

jagged gulch
#

like turns upside down

#

would a clamp there stop that from happenin or nah notlikethis

short hazel
#

Yeah, and a clamp won't prevent that unfortunately because the clamping should be applied to the world rotation. I guess you could make your hierarchy backwards through, the camera movement is done on the child of the object the recoil gets applied to

#

My code does not clamp so I think it's using that method

#

Or I never shot fast enough to rotate past 90ยฐ, but this gets mitigated a lot when you apply the second part of recoil, returning back to zero progressively

jagged gulch
#

Im considering leavin it as is at this point cause I cant figure out how to get past this block

#

notlikethis unity dev really beatin my ass here cause this shit haaarrrrddddddd

#

I think the original code would work fine for other guns but I can fine curb the shotgun by just making the spread wide

short hazel
#

Or lower the firing rate for the recoil to have time to return back to its original rotation

jagged gulch
#

oh nah I was hopin for the opposite lol

#

I kinda wanted it to be slower so it took longer

#

thanks for the help tho, I wouldve never thought to try a few of those ideas out

short hazel
#

My system is like hybrid, it has two ways of applying recoil:

  1. Procedural like you have
  2. Following curves for finer, non-linear movement
    The code is a mess though lol, I'll redo it from the ground up if I'm ever bored enough to open Unity again lol
jagged gulch
#

Ive been at this recoil thing for two days when I shoudlve honestly been continuing work on my enemy ai stuff lol

#

my perfectionist self wanted the recoil to look like how I wanted tho so I tried in vain for these past few days

rare basin
#

why do I have this error

#

when im starting coroutine before disabling?

rich adder
short hazel
#

Most likely it really gets started at the end of the frame. Code up to the first yield gets executed immediately, but afterwards, mystery... on the c++ side

rare basin
#
    public void RespawnSquare(float delay)
    {
        StartCoroutine(SquareSpawnManager.Instance.RespawnCoroutine(this,delay));
        gameObject.SetActive(false);
    }
#

so i can turn this into a corutine

crisp token
#

anyone know if it is possible to get the vertices making a triangle given you have the triangle?

rare basin
#

and add extra yield for a frame betwene?

#
    public void RespawnSquare(float delay)
    {
        StartCoroutine(StartRespawningSequence(delay));
    }

    private IEnumerator StartRespawningSequence(float delay)
    {
        StartCoroutine(SquareSpawnManager.Instance.RespawnCoroutine(this, delay));
        yield return new WaitForEndOfFrame();
        gameObject.SetActive(false);
    }
#

looks ugly but maybe it works

short hazel
#

You need to start the coroutine on an active object, like

StartCoroutine(SquareSpawnManager.Instance.RespawnCoroutine(theOtherObject, delay));
theOtherObject.SetActive(false);

Now as long as the object this script is attached to stays active you're fine

rare basin
short hazel
#

No

rare basin
#

oww yea ok

#

i get it

#
    public void RespawnSquare(float delay)
    {
        SquareSpawnManager.Instance.StartRespawnCoroutine(this, delay);
        gameObject.SetActive(false);
    }
#

now its like that

#

and im starting the coroutine on SquareSpawnManager

#

which is a different object

short hazel
#

Yep that works

rare basin
#

works perfectly, tysm

tender stag
#

how does one round that up to two decimal places
weightText.text = weight + "kg";

#

like this?
weightText.text = weight.ToString("F2") + "kg";

latent idol
#

I have a "Score" script that is supposed to update the score on my TextMeshPro component, but I can't seem to get a reference to that component in the script. What component is the script supposed to be attached to?

#

Some of the stuff I've tried but I keep getting object reference null error

slender nymph
#

use TMP_Text rather than TextMeshPro. TextMeshPro is the non-UI text but you probably want the UI one which is TextMeshProUGUI. however they both inherit from TMP_Text so you can use that for either one with no issues

latent idol
#

OK I'll try that thanks

slender nymph
#

i would also recommend just dragging the reference into the inspector rather than using GameObject.Find then GetComponent

latent idol
#

Tried that too but it's not letting me for some reason

#

That's why I think the script is attached to the wrong component

slender nymph
#

is this script perhaps on a prefab?

slender nymph
#

your scripts are components

latent idol
#

my terminology is not great lol

#

should this be on the TMP_Text?

slender nymph
#

you have not switched to the correct variable type

latent idol
#

not sure how to do that tbh

slender nymph
#

your myText variable needs to be of type TMP_Text not TextMeshPro

rich adder
latent idol
#

OK I did that but I still can't associate an asset to that variable, which is why I think the script is on the wrong asset (prob not the correct terminology)

slender nymph
#

is the Score component on a prefab?

latent idol
#

no it's on a ui element

slender nymph
#

that doesn't preclude it from being a prefab. but so long as both objects are in the scene at the same time and you have the correct type for your variable then you can just drag the text object in

#

if it is still not working then screenshot the unity editor so that we can see both the hierarchy and the inspector while you have this object selected so we can see the Score component in the inspector

latent idol
slender nymph
#

okay so if you drag either the component in or the entire Text(TMP) game object in, what happens?

latent idol
#

it doesn't do anything

slender nymph
#

wdym it doesn't do anything? can you record what happens?

latent idol
#

yes

rich adder
#

the font is still the old Text component

slender nymph
#

oh shit, i didn't even notice that. how did that even happen

latent idol
#

so how do i change it to the proUGUI component

slender nymph
#

remove the Text component and add the TextMeshProUGUI component

rich adder
#

make sure its the UI one

latent idol
#

wait how do you get to that one

#

cause i have to go under game objects

slender nymph
#

this is the add component menu

latent idol
#

and see textmeshpro in the ui

#

how do i get to the add component menu

polar acorn
slender nymph
#

that's the button in the inspector if you scroll all the way down. it literally says Add Component

latent idol
#

ok found it

#

ok now a new error pops up

#

the object of type "TextMeshProUGUI" has been destroyed but you are still trying to access it

slender nymph
#

well it seems like you're trying to access something after it has been destroyed. you'll need to show the context for where this error is happening

#

at a complete guess though, i'd say it's either you forgot to unsubscribe from a static method when an object was destroyed/scene unloaded

latent idol
#

its refering to an internal unity script

#

i did not write this

slender nymph
#

is this error happening during play mode?

latent idol
#

yes

slender nymph
#

and what happens in the scene that triggers this error?

latent idol
#

interacting with the power pellets

#

in my game

slender nymph
#

well that means almost nothing to me without code context. i'm assuming that interacting with those pellets tries to change the text property of the TMP_Text object?

latent idol
#

yes

#

to get a higher score

slender nymph
#

can you show the code that tries to use the TMP_Text object?

#

and can you also show the entire stack trace for the error

latent idol
#

u want the whole script

#

?

slender nymph
#

sure

#

use a bin site ๐Ÿ‘‡ !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.

tender stag
#

can i use the same velocity variable for 3 different smooth damps?

#

or is it gonna go weird

latent idol
#

ok its not letting me accept the terms

#

got it

#

had to use a diff one

slender nymph
#

you're still using GameObject.Find and GetComponent so you're overwriting the myText variable in start. if you've dragged the component in, then just remove those lines since they become unnecessary

#

but i'd still like to see the stack trace for the error to determine if it even is related to your code

latent idol
#

how do i send you the error stuff

#

cause idk how to be able to send that

slender nymph
#

just screenshot it

latent idol
#

the object one repeats

slender nymph
#

okay so first, always focus on the first error in your console. that is causing the subsequent errors. so make the changes i suggested [here](#๐Ÿ’ปโ”ƒcode-beginner message) and it should work just fine

latent idol
#

i will try it

#

and let you know if anymore problems arise

latent idol
slender nymph
#

show the stack trace for the errors and what the code currently looks like

latent idol
slender nymph
#

and the code?

rich adder
#

myText = temp.GetComponent<TextMeshPro>();
what is this line for

latent idol
#

its the same code i linked earlier

slender nymph
#

it shouldn't be

rich adder
#

is that line causing issue?
myText being re-assigned TextMeshPro from temp

latent idol
#

i got rid of that line

slender nymph
#

show the updated code

rich adder
#

ohh maybe send the code thats up to date lol

latent idol
#

there

slender nymph
#

add this line to Start: Debug.Assert(myText != null, $"myText is null on {name} {GetInstanceID()}", gameObject); and show what it prints

#

oh wait. your updated code is wrong. you're still using the wrong variable type for some reason

latent idol
#

oh which one should it be

slender nymph
#

TMP_Text

neat tulip
#

hey im trying to make my character be able to move and can't find any scripts that make me able to

#

on 2d

#

no gravity also

slender nymph
#

there are plenty of tutorials you could watch for that

neat tulip
#

ok

latent idol
#

im gonna take a break from this project i have been at it for like 4 hours

#

thanks for the help @slender nymph

unkempt carbon
#

does anyone know if there is a way to randomize the mass of an object?

slender nymph
#

generate a random number using something like Random.Range then assign it to the mass property on the rigidbody

unkempt locust
#

where I find this in unity?

#

i not find in "Windows"

#

please help me

slender nymph
#

this is a code channel. also depending on your version the navigation workflow has changed and you're clearly watching a tutorial from a really old version

ashen ferry
#

I have this scene with basic stuff always existing like controls and ui but star + planets and skybox changing across star systems should I use additive scene loading for planets it must exist for a reason but idk why I shouldnt just destroy those dynamic things and rebuild in same scene lol

unkempt locust
slender nymph
#

there's documentation pinned in that channel that you can read

oblique gazelle
#

help me with inventory pickup please

#

anyone

#

i cant pickup and add 5 items to inventroy

summer stump
oblique gazelle
#

I can pickup two

#

im gettting error on the second weapon

summer stump
oblique gazelle
#

So I am using raycast

#

  // ray from the camera 
  if (Physics.Raycast(ray, out hit))
  {
      hitObject = hit.transform;
      float distance = hit.distance;
      
      if(distance < 9 && hitObject.tag == "Weapon" || hitObject.tag == "Item")
      {
          showLabel = true; // SHOW THE PICKUP LABEL  


          // PICKUP THE GUN  
          if (Input.GetKeyDown(KeyCode.E))
          {
              if (weaponAmount > 0)
              {
                  Debug.Log("altease one weapon in hand");
                  SwitchWeapon(hitObject);
              }
              Debug.Log("weapon pickup first " + hitObject.name);

              Transform transforms = GameObject.Find("gunContainer").transform;


              if(!weapons.Contains(hitObject))
              {
                  PickUP(hitObject.transform);
              }
          
          }
      }

      else
      {
          showLabel = false; // SHOW THE PICKUP LABEL  
      }
  }

  if(!equipped && Input.GetKeyDown(KeyCode.G))
  {
      equipped = true; 
  }


// DROP THE GUN  
  if (equipped && Input.GetKeyDown(KeyCode.G))
  {
      equipped = false;
      Transform game = GameObject.Find("gunContainer").transform;



      DropGun(weapons.ElementAt(weaponAmount));
  }
#

@summer stump

summer stump
#

So the error mentions "MoveNextRare"
What is that code?

grave jay
#

if i were to make a script to store values, should i leave it as monobehaviour or change it?

ivory bobcat
#

Should it be a component or not?

grave jay
#

yeah

summer stump
#

The script must inherit from that (or Component or Behaviour, but keep it simple and use MonoBehaviour) to be a component of an GameObject

static cedar
#

That's a lotta nesting. UnityChanThink

static cedar
summer stump
static cedar
#

Yeah i tried, it asks for an attribute that you can't even use.

summer stump
#

I just felt like someone would point it out, so I was covering my a

static cedar
summer stump
summer stump
grave jay
#

What is the easiest way to detect how a button is pressed (GUI)?

buoyant knot
#

wdym how?

tough lagoon
timid quartz
#

I am having trouble organizing an algorithm I want to build. I have a list of characters in a row and I want them to switch their order in the scene based on the current active character, so if the index is 1, I want character A to be first, character B to be 2nd, etc. And if the index is 4, I want character D to be first, and then A to be 2nd. I just have to set the sibling index of the characters to get the display to work right, but I have no idea how to do the math within the for loop to make it work for any length of Active Players. Any ideas?

// handle the display order
// if we have a list of 4, and the current index is 3, then the 3rd one is 1st, the 4th one is 2nd, the 1st one is 3rd, and the 2nd one is 4th
// 1 = 3rd
// 2 = 4th
// 3 = 1st
// 4 = 2nd

for (int i = 0; i < ActivePlayers.Count; i++)
{
ActivePlayers[i].transform.SetSiblingIndex( ??? );
}

hearty ivy
#

can anyone help me with my vs code intellesence

#

i regenerate my project files and reloaded window

#

and got an error message

#

RemoteInvocationException: Sequence contains no elements

hearty ivy
#

boshhy

#

you are a saint

#

god bless u

queen adder
queen adder
#

oh lmao its a message reference

pearl lodge
queen adder
#

I thought bro mentioned the channel ๐Ÿ’€

queen adder
pearl lodge
#

believe me it confused me to. I looked up my old message and copied message link, and hit paste and thats what it came up with, but it worked lol

queen adder
#

discord is getting a lot cooler with its references

#

But there is many videos about how to get intellisense working in vs code

queen adder
#

๐Ÿ’€

#

real

vestal grove
#

Is there a hotkey to press this "arrow"

#

for sprites

grave frost
vestal grove
#

Thank you

#

it worked

nocturne parcel
#

Weird question but
Is it possible to add a type to a variable?
Like var i = int or something like that
I have this gigantic function https://pastebin.com/gj85Lm5L
And it is already complicated enough

#

I still need to repeat it for the land tiles

#

Would be easier to just change the type on tilemap.GetTile<T> instead of repeating everything again

#

Is that possible?

teal viper
#

There's the Type type(no pun intended). That you can use to store a type in a variable.

#

Though, perhaps you're doing somehting wrong if you need to rely on it.

nocturne parcel
#

That's actually exactly what I need tho

#

Thanks

teal viper
#

You can't use it with generics though, if that's what you plan.

nocturne parcel
#

Oh

#

Yeah that's rough

#

Can I use something like tilemap.GetTile<typeof(tile)>

#

And tilecan be my two different types of tile?

teal viper
#

No, I don't think you can do that. I think generics are evaluated at compile time, when tile is undefined.

#

Perhaps you can use polymorphism to solve your issue. Not entirely sure what you're trying to do though.

nocturne parcel
#

I'm using it to check types of neighbors

#

It gives me inconsistent results if I use GetTile returning TileBase

teal viper
#

You can just check the type of TileBase

nocturne parcel
#

For example, if I use is operator to check the type, it is always returning false

teal viper
#
if(tile is WaterTile water)
{  
  //do something with water tile
}
else//...
nocturne parcel
#

When I use Equals, i get a null reference too for some reason lol

nocturne parcel
teal viper
#

I don't see how Equals is relevant here, but is should work

teal viper
nocturne parcel
#

Sure

#

Maybe I was just doing something wrong

#

When comparing

#

I remember I may have had cast the tile before comparing

#

I'll try again

#

Thanks for the help tho

teal viper
#

Yeah, try the is again and see if it works.

nocturne parcel
#

Tbf, just using type checking would accomplish the same thing I'm doing rn, same lenght

#

As I'm checking type already, just differently

teal viper
#

I guess so

nocturne parcel
#

So yeah, thanks for the help anyway

#

Would be nice to have a way to change the type of a generic in runtime

teal viper
#

You can use polymorphism perhaps:

MyTileBase t = GetTile<MyTileBase>(pos);
t.DoSomeSpecificLogic();

And then override the DoSomeSpecificLogic in each of your types inheriting from MyTileBase.

nocturne parcel
#

Wait, that's actually a very good idea

#

thanks

teal viper
#

Or something more intricate, depending on your needs.

nocturne parcel
pearl lodge
nocturne parcel
#

Oh

#

I mean, considering it's me trying to clean up a procedural generated island

teal viper
#

Loops and checking neighbors are very common in different algorithms.

nocturne parcel
#

It may have similarities

#

I was trying to do a flood fill algorithm without it being a flood fill algorithm

#

That's why it isn't the best code out there :p

pearl lodge
# nocturne parcel It may have similarities

I don't know what your end task is but if it has anything to do with changing tiles to a different 'tiletype' depending on what the neighbors are, then you will most likely need a "currentState" of the tiles and "nextState" of the tiles.

#

You don't want to change them as your doing your for loop

nocturne parcel
#

Oh, it's not continuous. it's just one step on the island generation to clean up single out tiles.

#

So I don't get a random single water tile inside the island

snow mural
#

So Iโ€™m making a card game, where up to 5 hands are in play (5 cards per hand). The last card is face up and the person with the highest card will be the leader for the round.
However, if multiple people share the highest card I donโ€™t know how to handle the situation.

So far Iโ€™ve just stored all the 5th cards in a List<GameObject>.

nocturne parcel
#

Care to detail more your problem?

teal viper
snow mural
#

How to code it. I want only 1 leader, and when there are multiple people with the same highest cards I want to deal another card to only those hands and check again if one has a higher card.

teal viper
#

So, only one person can have the highest card and when they pick it, no one else can?
Is that what you want?

snow mural
#

So potentially, but very low probability, having the same highest card can happen several times

snow mural
magic smelt
#

How can i call the GameObject OnMouseEnter from an array of GameObjects?

[SerializeField] private GameObject[] gameObjects;

private void Start()
{
    foreach(var gameObject in gameObjects)
    {
        //Subscribe to OnMouseDown / OnMouseEnter?
    }
}

private void OnMouseDown()
{
}

private void OnMouseEnter()
{
}
teal viper
nocturne parcel
#

Tho I suspect you wouldn't need to do that if this is an event

magic smelt
gaunt ice
#

actually you should get component first

#

but i will not suggest this, instead change the gameobject[] to some monobehaviour[]

nocturne parcel
#

You are subscribing the function... to itself?

snow mural
magic smelt
#

Well im kind of puzzled.. All I want to to do is handle the OnMouseEnter of gameobjects inside of 1 script instead of having like 100 scripts.

When I make a single script to do it for each object, it works very well

magic smelt
nocturne parcel
#

So, that's how events are for, but you are doind it wrong

#

Lemme see if I can find a tutorial

#

For events

magic smelt
nocturne parcel
#

Good resource about events

magic smelt
teal viper
nocturne parcel
#

Also, I'm pretty sure you can use built in Unity functions for that? Just make a ray coming out of the mouse, and let the ray script handle what to do when the mouse enters, not each object

cosmic dagger
snow mural
nocturne parcel
#

Like, a built in function lol

teal viper
nocturne parcel
#

It already does a raycast

#

Cool

uncut shoal
#
        foreach (var item in colliders) Destroy(item);

        var actualWidth = pixelSize * size.x;
        var actualHeight = pixelSize * size.y;
        var actualHalfSize = new Vector2(actualWidth, actualHeight) / 2;

        foreach (var rect in PDCG.GenerateColliders(pixels, size.x, size.y))
        {
            var box = gameObject.AddComponent<BoxCollider2D>();
            box.size = new Vector2(rect.size.x, rect.size.y) * pixelSize;
            box.offset = rect.center * pixelSize - actualHalfSize;
        }```
#

why does this only work the first time

cosmic dagger
uncut shoal
#

after its used for the first time, whenever I use it afterwards, it only deletes the colliders but doesn't generate new colliders?

gaunt ice
#

you add multiple boxcolliders to same gameobject?

uncut shoal
#

yes

gaunt ice
#

if it doesnt create new collider on the object, the foreach loop is not execute so PDCG.XXXX iterate nothing and yield return nothing

uncut shoal
#

yea I think I found the problem

#

yep I did

#

thanks!

versed light
#
        while (transform.childCount > 0)
            DestroyImmediate(transform.GetChild(0).gameObject);```

why would this cause infinite loop
#

doesnt make sense to me

north kiln
#

Afaik, it shouldn't. But it does seem like a very bad way to destroy all the children

#

Use a reverse for loop

nocturne parcel
#

Also, 2 lines of code doesn't really show much lol, show everything of the while loop

#

Oh, it's only one line

north kiln
#

@versed light (missed how long ago you posted, have a ping)

versed light
#

maybe it acts different in edit mode

nocturne parcel
#

I have a question about tilemap.RefreshAllTiles. Does it call the RefreshTile of each tile?

versed light
#

press f12 on the function and take a look at the code for it

#

unless they made it external

nocturne parcel
#

I'm having some weird behaviour when calling it

versed light
#

(f12 for visual studio) might be a different key if you use a different ide

nocturne parcel
#

Thanks, I'll try that

#

But I guess my problem is with tiles being scriptable objects (I'm passing a value to a custom tile class)

#

Hmm I'll see what I can do

#

ye, the tiles were getting the last value set, all of them

#

So I actually need to not refresh my tiles

tawdry rock
#

Hoi. Is the Space/Enter button considered in unity with some sort of "pressing" function? I mean like when you use Tab button in the browser to select a button and pressing enter will press that button like you clicked on it. I hope it's clear what i mean.
I noticed in my game if i open my inventory and there is a button to drop stuff, when i click on it and press space or enter the button still gets "clicked". If i just open the inventory and press space/enter nothing happens just after 1 click registered (with mouse) for that button.
Im pretty sure its some kind of wierd button mechanism because if i click once more anywhere and then try to press space/enter it no longer registering as i trying to press it.

main karma
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class PlayerData
{
    public int shardTotal;
    public bool is_tutorial_done;
    public struct Level
    {
      
        public int shards;
        public float finishTime;
        public bool is_level_done;
    }
    public Level[] lvl = new Level[10];

    public PlayerData()
    {
       
    }
}```
how do I initialize the struct (lvl) in the constructor instead? (if that's even possible) because when I do it throws me the null reference exception
gaunt ice
#

you mean lvl[some index].something gives you an NRE?

solar tide
#

This code works fine. I simply put in the reference gameobject for the SwitchUnit in the inspector.
But what if I want SwitchUnit to be more than 1 object?
Maybe objects that has a certain tag or rather any gameobject that is specifically in that position in the if statement?
What do I write?

main karma
solar tide
main karma
#

even if I create a new PlayerData object in another script and try to initialize any lvl I get NRE

#

only way it works is w the syntax I put above

gaunt ice
#

i think it is impossible to throw NRE in your case.. maybe try lev=new Level[10] in the constructor first

#

level is struct

north kiln
#

You have to initialize the array before you access/set its members, not doing that is the only way you would get an NRE

main karma
#

ah it's cuz I Load first and save later, so they never get initialized unless I save the game, so I try to load nothing

analog depot
#

Hi - if I had an object I wanted to rotate around another object, to point at a third object...
o
. x z

So rotate o around x (to .) to point line up with z - any smart ways?

#

I know I can rotatearound x, but I'm not sure of the cleanest way to figure out the angle, or indeed if tehre's a shortcut

shy cloud
#

Does anybody know why this (C#) code isn't working? It doesn't give me an error, it just doesn't do anything. I have the event triggers set up and everyting.

north kiln
#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

shy cloud
north kiln
#

It needs to be on an object like a Graphic or Collider. You cannot get UGUI events without an appropriate thing for the event system to click

shy cloud
north kiln
#

Events are sent using various scripts, the one on the canvas is called the Graphic Raycaster

#

it looks at Graphics under the canvas and sends events if they were relevant

#

Events are only sent to the gameobjects that have the Graphic (like an Image) component on them. If you have a Canvas object alone, there is no event sent

short hazel
#

You also need an Event System in your scene, in case you got rid of it by accident

#

An object named "Event System" in your hierarchy

shy cloud
shy cloud
north kiln
#

A Sprite Renderer is not a Graphic

shy cloud
#

what kind of graphic shoud I add then bc I dont want to affect the look of the sprite

north kiln
#

Image is the component you use inside of a Canvas

shy cloud
#

like that

shy cloud
ivory bobcat
#

Or just give it a collider2d

shy cloud
ivory bobcat
#

Something that's able to get bounds check

#

Maybe you did not have a physics 2d raycaster for the camera?

shy cloud
ivory bobcat
#

Graphics raycaster is a component for canvas

shy cloud
#

The canvas has one

north kiln
#

That's correct, it does not need to be anywhere else but on canvases and subcanvases

#

If it's working, there's nothing more to worry about

ember musk
#

Will methods in Debug be built into my packed game, and cause unnecessarily performance overhead?

keen dew
#

Logs yes, asserts no. Logging in builds can be switched off in player settings.

tepid cove
#

im making a vr shooter and i have 1 problem, im using a bullet model (not a spheare) and my bullet flys facing one directions, its shoots in the right direction but doesn't face the right direction, lets say i turn 90 degrees my bullet i just shot will be flying at 90 degrees which looks goofy, i dont know how to fix this and i dont want to make the bullet a sphear and ignore it.

#

this is my code

slender nymph
#

assign its transform.forward to the spawnPoint.forward since that is the direction it is being fired in

#

alternatively you can pass in the spawnPoint.position and spawnPoint.rotation to Instantiate and you won't have to manually assign those on the following lines

tepid cove
slender nymph
#

assign its transform.forward to the spawnPoint.forward
is literally how

#

i'm not going to write the code for that for you

tepid cove
#

okay okay, thanks tho

slender nymph
#

and if you read the second message i sent, you'll see an even easier way

queen adder
#

How to change clipboard text via code?

brave compass
queen adder
#

hmm i need a runtime thingy ๐Ÿฅน

spiral rain
#

So I have a list full of scriptable objects and I was wondering if you can get one scriptable object with just the name of that scriptable object for ex I have a scriptable object named Tom so I would search for Tom in my list

queen adder
#

Use a dictionary lookup system?

dusky vigil
#

I got a pickup and drop system but every time I drop the weapon the weapon is droped at the origin of the scene instead being droped at the current location. The only thing i'm doing in the script is unparenting the weapon from the character and disabling some scripts. help pls :(.

verbal dome
#

It might be overriding the guns local position to 0,0,0

#

And with no parent that becomes the world position

charred spoke
#

That or the rb might remember its last non kinematic position.

main karma
#

can JSON serialize structs?

#

or an array of structs to be exact

short hazel
#

Serialize structs, yes. Arrays, depends on the serializer

#

JsonUtility cannot serialize arrays directly, you have to wrap the array in a class and serieliez the class

queen adder
#

will i get problems if i load this from json?

queen adder
#

ooh another json pwoblem

main karma
short hazel
queen adder
#

i just used this JsonUtility.ToJson(MainCharacterController.mainCharacter);

short hazel
#

Well it's trying to serialize some components there, not sure what the behavior will be on deserialization

main karma
# queen adder i just used this `JsonUtility.ToJson(MainCharacterController.mainCharacter);`

same here, and I get this error when I try to use FromJson

Error occured when trying to read data from a fileC:/Users/Rob/AppData/LocalLow/myDevStudio/LIMBO RGB\data.limbo
System.ArgumentException: JSON parse error: Invalid value.
  at (wrapper managed-to-native) UnityEngine.JsonUtility.FromJsonInternal(string,object,System.Type)
  at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) [0x0005c] in <7fe3f96a6d704e1eaaf6ef514c2f5a51>:0 
  at UnityEngine.JsonUtility.FromJson[T] (System.String json) [0x00001] in <7fe3f96a6d704e1eaaf6ef514c2f5a51>:0 
  at FileDataHandler.Load () [0x00031] in D:\Unity Projects\LIMBO RGB\Assets\Scripts\DataPersistance\FileDataHandler.cs:34 
UnityEngine.Debug:LogError (object)
short hazel
#

Fields referencing components should probably be ignored

#

By decorating them with the NonSerialized attribute, probably

oblique gazelle
#

can someone help with inventory?

#

unity

short hazel
tepid cove
#

im still stuck on how to do this, tried googling how to assign them together. "+" gives me an error if i do spawnPoint.position + spawnPoint.rotation;

short hazel
#

Both will rotate the instantiated prefab accordingly, so it faces the same way as the spawn point

#

If you choose the second approach, you won't need line 27 also

tepid cove
#

thank you, the problem is when asking for help is that i dont know how to code, so all the terminology is alien to me, ive just been learning how to do what ive seen but when something new pops up im clueless

verbal dome
oblique gazelle
#

my inventory not wokring

#

I cant to see data about the item too

short hazel
jovial peak
short hazel
#

!vsc

#

Hm

tepid cove
short hazel
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

short hazel
#

There we go

#

Do the configuration guide first

verbal dome
tepid cove