#💻┃code-beginner

1 messages · Page 813 of 1

rough granite
#

you were already given your answer so whats the problem now?

rough granite
#

you, the last message Faywilds sent

sour fulcrum
#

faywilds link is the route 💯

supple flume
sour fulcrum
#

ohh i did not realise thats a new thing

rough granite
stuck parrot
#

question: how do I backup my code if i try to mess with my code and want to go back if I break stuff? For mow i copy the script and if something happens i rename the copy to the original and delete the broken. I know theres something like git but i dont know how to use that or if it even works with unity

frosty hound
#

onUnitCircle is new, so if you're on an old Unity it won't exist.

#

Just use insideUnitCircle and normalize the result 🤷‍♂️

slender nymph
supple flume
#

i use 2022 unity

sour fulcrum
frosty hound
#

That'll give you a vector of length 1, and then you can multiply it by however big you want the circle to be.

#

If you need it to be 3D yeah

frail hawk
supple flume
#

would onUnitSphere work but i ignore the z?

sour fulcrum
#

oh yeah to be clear osteel and boxfriend onunitsphere is not new

#

just circle

stuck parrot
naive pawn
#

git is not the terminal

rough granite
slender nymph
naive pawn
#

git is just the underlying system.

sour fulcrum
#

oh right different random range

naive pawn
slender nymph
safe latch
#

yo guys, want a smooth camera in a pixel art game (as in having damping) but I do not want pixel snapping. I know Godot can do this somehow, but I don't know about Unity. I have tried just about every plugin/addon asset that there is, and they all still have pixel snapping. I know you can do imperfect pixel art or whatever, but aren't there downsides to it? If not, how do I use imperfect pixel art for a smooth camera? any help is appreciated bc i'm REALLY lost on this tbh

naive pawn
#

it is not

rough granite
#

the website, repos, and account all lead to the same place though whats different?

naive pawn
#

github is a company/service for hosting and managing remote repositories

github desktop is a gui git client made by github

rough granite
supple flume
frosty hound
#

Inb4 it doesn't work. What is your actual goal with this random direction?

#

Because if it's to move the object from its current position to a random direction from its current position, this isn't that.

supple flume
#

i want an obejct to only move like this

frosty hound
#

But you haven't explained what you're actually trying to do.

sour fulcrum
#

does vector.normalize() actually modify itself or does that return a value (im asking cuz idk)

frosty hound
#

You want the object to move around a circle?

supple flume
#

and i want it to be random movement
instant change of position

supple flume
frosty hound
#

You want it to pick a random position, a distance away from itself, move to that position and upon arriving, pickg another random position?

supple flume
frosty hound
#

Sure.

  1. Pick a random direction via insideUnitCircle and normalize it.

  2. Multiply that value by the size of the circle you want (it'll be 1 by default when normalized)

  3. Calculate the point to move to by adding that value to the position of the fixed object

  4. Move your character to that point

  5. When it arrives, repeat the process

naive pawn
rough granite
naive pawn
rough granite
#

yeah yeah i got what you meant

naive pawn
#

cool, gonna keep that explanation handy for future questions

whole gulch
#

hi guys, so, I'm making a game for a project for school, and I'm going nuts over this, it is malfunctioning like crazy, can someone help me pls? The game starts on the main menu, and I press play, if I return to the main menu again and then press play again the character is nowhere to be seen, and when I change scenes the player does not change too, it was working and just stopped working. The console shows no errors and I started the project from scratch, just following youtube tutorials and altering it to what I wanted, I would really appreciate it if anyone who has time adopted it and helped me out. This are the videos of the problems mentioned

slender nymph
#

show relevant code

hallow sun
#

Do you have DontDestroyOnLoad on the player?
My guess its the player falls out of the screen and you forgot to set a starting position on load scene

near wadi
#

!code

radiant voidBOT
whole gulch
#

public class GameStateManager : MonoBehaviour
{
    public static GameStateManager instance { get; private set; }

    [HideInInspector] public string spawnFromName;
    [HideInInspector] public Vector2 playerPosition;
    [HideInInspector] public int sceneIndex;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void SavePlayerState(Vector2 position, int scene, string spawnName)
    {
        playerPosition = position;
        sceneIndex = scene;
        spawnFromName = spawnName;

        PlayerPrefs.SetFloat("PlayerPosX", position.x);
        PlayerPrefs.SetFloat("PlayerPosY", position.y);
        PlayerPrefs.SetInt("SceneIndex", scene);
        PlayerPrefs.SetString("SpawnName", spawnName);
        PlayerPrefs.Save();
    }

    public Vector2 LoadPlayerPosition()
    {
        if (PlayerPrefs.HasKey("PlayerPosX") && PlayerPrefs.HasKey("PlayerPosY"))
        {
            float x = PlayerPrefs.GetFloat("PlayerPosX");
            float y = PlayerPrefs.GetFloat("PlayerPosY");
            return new Vector2(x, y);
        }
        return playerPosition;
    }

    public string LoadSpawnName()
    {
        return PlayerPrefs.HasKey("SpawnName") ? PlayerPrefs.GetString("SpawnName") : spawnFromName;
    }

    public int LoadSceneIndex()
    {
        return PlayerPrefs.HasKey("SceneIndex") ? PlayerPrefs.GetInt("SceneIndex") : sceneIndex;
    }
}```
#
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

public class SavePoint : MonoBehaviour
{
    public string savePointName = "LastSavePoint";
    public Animator animator; 

    private bool playerInRange = false;
    private GameObject player;

    private void Update()
    {
        if (playerInRange && Keyboard.current.eKey.wasPressedThisFrame)
        {
            ActivateSavePoint();
        }
    }

    private void ActivateSavePoint()
    {
        if (player == null) return;

        var pd = player.GetComponent<Damagable>();
        if (pd != null)
            pd.Health = pd.MaxHealth;

        var inimigos = GameObject.FindObjectsByType<Damagable>(FindObjectsSortMode.None);
        foreach (var d in inimigos)
        {
            if (d.CompareTag("Enemy"))
                d.Health = d.MaxHealth;
        }

        GameStateManager.instance.SavePlayerState(player.transform.position, SceneManager.GetActiveScene().buildIndex, savePointName);

        if (animator != null)
            animator.SetTrigger(AnimationStrings.interacted);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            playerInRange = true;
            player = collision.gameObject;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            playerInRange = false;
            player = null;
        }
    }

    public static void SaveGame(Vector2 position, int sceneIndex, string savePointName)
    {
        PlayerPrefs.SetFloat("PlayerPosX", position.x);
        PlayerPrefs.SetFloat("PlayerPosY", position.y);
        PlayerPrefs.SetInt("SceneIndex", sceneIndex);
        PlayerPrefs.SetString("SpawnName", savePointName);
        PlayerPrefs.Save();
    }
}
#

public class PlayerBootstrap : MonoBehaviour
{
    [SerializeField] private GameObject playerPrefab;

    public static bool playerSpawned = false;

    public GameObject SpawnPlayer()
    {
        Vector2 spawnPos = GameStateManager.instance.LoadPlayerPosition();
        string spawnName = GameStateManager.instance.LoadSpawnName();

        GameObject existingPlayer = GameObject.FindGameObjectWithTag("Player");
        if (existingPlayer != null)
            Destroy(existingPlayer);

        GameObject player = Instantiate(playerPrefab, spawnPos, Quaternion.identity);
        DontDestroyOnLoad(player);
        playerSpawned = true;

        return player;
    }
}
wintry quarry
whole gulch
#
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour
{
    [SerializeField] private int firstGameSceneIndex = 1;
    [SerializeField] private string firstSceneSpawnPointName;

    public void PlayGame()
    {
        int sceneIndex;
        string spawnName;

        if (PlayerPrefs.HasKey("SceneIndex") && PlayerPrefs.HasKey("PlayerPosX"))
        {
            sceneIndex = PlayerPrefs.GetInt("SceneIndex");
            spawnName = PlayerPrefs.GetString("SpawnName");
        }
        else
        {
            sceneIndex = firstGameSceneIndex;
            spawnName = firstSceneSpawnPointName;
        }

        if (GameStateManager.instance != null)
        {
            GameStateManager.instance.spawnFromName = spawnName;
        }

        if (ScreenFader.instance != null)
        {
            ScreenFader.instance.FadeToScene(sceneIndex, spawnName);
        }
        else
        {
            SceneManager.LoadScene(sceneIndex);
        }
    }

    public void QuitGame()
    {
        Application.Quit();
    }
}```
radiant voidBOT
whole gulch
#
using UnityEngine.SceneManagement;

public class ColorMove : MonoBehaviour
{
    public int sceneBuildIndex;
    public string spawnFromName;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("Player"))
            return;

        if (ScreenFader.instance != null)
        {
            ScreenFader.instance.FadeToScene(sceneBuildIndex, spawnFromName);
        }
        else
        {
            if (GameStateManager.instance != null)
            {
                GameStateManager.instance.spawnFromName = spawnFromName;
            }

            SceneManager.LoadScene(sceneBuildIndex);
        }
    }
}```
solar hill
#

@whole gulch please dont ignore the bot message

#

use pasting sites

whole gulch
whole gulch
wintry quarry
whole gulch
wintry quarry
solar hill
whole gulch
wintry quarry
solar hill
#

You are supposed to be keeping track of it though

whole gulch
#

I know, I was

hallow sun
#

Still not seeing anything that says "when starting this scene, place the player in a platform" if you

wintry quarry
#

I actually think you're probably just not using SavePoint.SaveGame at all and it can and should be deleted

rough granite
# hallow sun Still not seeing anything that says "when starting this scene, place the player ...

i think it's here v

    public GameObject SpawnPlayer()
    {
        Vector2 spawnPos = GameStateManager.instance.LoadPlayerPosition();
        string spawnName = GameStateManager.instance.LoadSpawnName();

        GameObject existingPlayer = GameObject.FindGameObjectWithTag("Player");
        if (existingPlayer != null)
            Destroy(existingPlayer);

        GameObject player = Instantiate(playerPrefab, spawnPos, Quaternion.identity);
        DontDestroyOnLoad(player);
        playerSpawned = true;

        return player;
    }
``` though im not sure if the method is even being called
whole gulch
whole gulch
#

atleast it should do that

rough granite
whole gulch
#

so I should delete savepoint.savegame?

safe latch
#

Guys, why does the gun and the background like glitch backwards and forwards and go from blurry to not blurry?

rough granite
safe latch
hallow sun
#

@whole gulch Add some Debug.Logs() on OnSceneLoaded and SpawnPlayerRoutine (GameLoader.cs) it has many Debug.LogWarning s but none are being used?
Very suspicious, i googled it and some people report OnSceneLoaded doesnt trigger for them so maybe thats the problem.

naive pawn
safe latch
rough granite
# radiant void

did the first 2 sites go under they both gave me a 502 error

whole gulch
hallow sun
#

just add some to see which code is being used, for example if this is the one being used:
spawnPos = GameStateManager.instance.LoadPlayerPosition();
because there is no name, then the error is probably on LoadPlayerPosition

whole gulch
#

like this?

rough granite
#

sure but also add some to the save and load methods to see the data that is being saved and loaded when they are being saved / loaded

whole gulch
#

I don't think I made what u wanted

#

probably I'm being dumb rn srry

rough granite
#

i mean like like you add a
Debug.Log($"Saved player position: {position}"); in the save method and a Debug.Log($"Loaded player position: ({x}, {y])"); before the return new Vector2(x, y ; in the LoadPlayerPosition method

hallow sun
#
if (!string.IsNullOrEmpty(spawnName))
{
  GameObject spawnPoint = GameObject.Find(spawnName);
  if (spawnPoint != null)
  {    
    Debug.Log("Loaded position from spawnPoint");
    spawnPos = spawnPoint.transform.position;
  }
  else
  {
    Debug.LogWarning($"Spawn point '{spawnName}' não encontrado!");
  }
}
else if (GameStateManager.instance != null)
{
  Debug.Log("Loaded position from LoadPlayerPosition");
  spawnPos = GameStateManager.instance.LoadPlayerPosition();
}```
something like this
rough granite
#

whats não encontrado! :?

hallow sun
#

didnt find in portuguese i think

#

that one was already there

rough granite
#

u think ~_~

whole gulch
rough granite
#

ahh

whole gulch
#

exactly

#

some of the commentaries are in portuguese

#

I really should start to be more consistent

#

well, I add it but nothing showed on the console

#

I tried to save the game, enter and reenter

hallow sun
#

oh so none of the code is being called

whole gulch
whole gulch
#

oh no

#

I have 1 month to finish this and it is like, not half done yet💀

#

I'm cooked

hallow sun
#

did you add debugs to the OnSceneLoaded to see if at least that one is being called?

whole gulch
#

I added this

solar hill
#

Also make sure you didnt turn off debug logs in the console

whole gulch
#

idk if it is right

hallow sun
#

and make sure youa actually placed the script, sometimes we forget and this one doesnt seem to be a static Instance so it has to be in every scene

hallow sun
whole gulch
#

when I press play and enter the game this appears

whole gulch
#

ok, so the non-existing character when switching scene comes from a poor configurated vcam, I'm trying to solve that now

whole gulch
#

if u guys or anyone has an idea of what I can do to solve it or wants to help dm me pls

polar acorn
#

What is the issue

#

This has been going on for a while I don't know what the actual question is

whole gulch
polar acorn
#

So, is the player actually in the scene? If so, what is their position and what is it supposed to be?

whole gulch
#

when I change scene I have seen that the player is on the scene and in the position that the game starts, it should be on the position stated by the color move, for exemple, it should spawn in the object SpawnFromHollow

#

and the vcam isn't working in any scene other the the first one

hallow adder
#

is there a SavePoint-Hollow transform in the Blue-Pre scene? you should add more logs or learn to use breakpoints

polar acorn
whole gulch
whole gulch
#

or gameloader?

#

or playerbootstrap, I think it is this one

polar acorn
# whole gulch isn't it colormove's job?

You kind of fired thirty scripts out of the window of a moving vehicle so if you have code doing something you should probably share the relevant stuff because I'm not going to read every single script you posted

#

What specific function is supposed to be moving the player at the start of the scene

whole gulch
#

spawnplayerroutine inside gameloader

#

it should be this one

#

i'm sorry for the confusion

polar acorn
#

So, the player is a prefab, and they're a DDOL object. This means anything in the scene that referred to the player in the scene is going to get recreated without that reference when the scene reloads.

#

If you want the player to be persistent, you're going to need to ensure nothing in the scene is getting that reference set in the inspector anywhere

#

And what object has this script on it? You're subscribing in OnEnable, is this object itself a DDOL or is it in the scene? If it's in the scene you're reloading, the OnEnable is going to run and add another subscription to sceneLoaded

whole gulch
polar acorn
whole gulch
#

it should go to spawnfromhollow on the blue scene

#

idk why it tries to go there

polar acorn
#

You're logging spawnName

#

If it's logging SavePoint-Hollow that's the value you have for spawnName

glad shore
#

how should i set the velocity of my players rigidbody in a 2d movement script?

whole gulch
polar acorn
#

Instead of thinking about what it should do, check what it is doing

#

Follow the breadcrumbs. See where spawnName comes from, and see if that value is what you expect. If it's not, see where that is getting the value, and so on until you find where it's becoming something you don't want

whole gulch
polar acorn
whole gulch
#

ok, I changed a few scripts and it looks like it is solved

#

I think

rocky wyvern
#

I am using some non mono classes with delegates; is there any easy way to unsubscribe when those objects are deallocated by gc?

#

or do i just have to be really really careful and do it manually

#

hmm though actually now I think about it this is a nonsense question because it wouldn't be being collected by gc if it is still subscribed

#

nvm!!!

golden canopy
#

guys is there a way to get the normal from an overlapsphere

teal viper
stoic sage
#

Is there some easier way of making a moveset without having a spaghetti of if (Input.

crimson sluice
#

Hey can anyone else tell me why c# isn't showing when I am trying to script something or is MonoBehaviour do the same thing?

wild cove
#

Monobehaviour is a vanilla script with a bit of stuff in it that uses C#, so yes, use monobehaviour. From what you said I think it is pretty much the same thing you're looking for.

crimson sluice
#

ok sounds good thank you

cosmic dagger
hardy wing
#

Are there any resources on where to learn how movement scripts are written with kinematic rigidbodies?

wild cove
#

I'm trying to make this function in my game where when the drill (the square looking thing going towards the capsule) hits the mole (the player) it reloads the scene, but for some reason nothing is working when the mole goes towards it and is in the box collider.

teal viper
ornate cosmos
# wild cove I'm trying to make this function in my game where when the drill (the square loo...

First try to use Debug. Log in OnTriggerEnter to output a message and confirm that the collision event method has been called. Additionally, if both of your objects have IsTrigger enabled and both have non kinematic rigid bodies with simulation enabled, then OnTriggerEnter should be callable. The OnTriggerEnter method is a method that can be successfully called as long as there are triggers in two game objects

sour fulcrum
#

one object

#

both don't need to be triggers

ornate cosmos
#

In this scene, both the Player and the Cube have a non kinematic rigid body with simulation enabled. The Player has gravity disabled and is waiting for the Cube to collide. They both have a collider, and as long as the collider of a certain game object is used as a trigger, the OnTriggerEnter method in the script on the Cube will be called

sour fulcrum
#

only 1 object needs a rigidobdy aswell

ornate cosmos
#

yeah, just cuz his scene he used 2 rigidbody, so i use 2 to show him how it works

hardy wing
teal viper
hardy wing
# teal viper You don't need to solve collisions. There's unity api for that, like casts, over...

Well you would still need to solve collisions because casting rays, spheres, boxes and what not wouldn't make it so I don't be inside objects, it would just cast a ray. And then it's also about where to cast a ray from. Center? Top? Bottom? All? Maybe even more in-between? All these questions feel like it's a complicated topic. I'm interested enough to dive into that rabbithole which is why I'm asking if there's any resources which I could read into. I also considered using Godot's CharacterBody2D as a reference implementation to see how they deal with their collide_and_slide algorithm.

teal viper
# hardy wing Well you would still need to solve collisions because casting rays, spheres, box...

What you're asking is basically how physics engines work. To put it simply, you have 2 options:

  • detect collision ahead of time with rays/casts and adjust the object velocity such that it doesn't overlap with the hit object.
  • detect and overlap after the collision happened, then calculate a depenetration velocity/displacement and apply it to your object.

If you want to learn down to Avery deep level might want to look for resources on physics engines independent of any specific game engine.

hardy wing
#

Mhh that makes sense. Sooo, are there any resources I can look into? dogekek Not sure if I can find some books, so maybe that. But from the kind of your responses I'm judging there's no well-known or popular thing.

teal viper
#

I don't know if there are any "good" resources. There are probably plenty of resources in general if you Google. This is not really something every unity developer has a sticky note on their fridge for.

hardy wing
cosmic dagger
#

!code

radiant voidBOT
real thunder
hardy wing
real thunder
#

that's a very different topic from general physics

#

also pita

#

google rigidbody character controller or something

celest depot
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class RollRight : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private bool isPressed = false;
    public GameObject Player;
    public float rollSpeed = 25f;
    private float rollInput = 0f;
    private float rollAcceleration = 2.5f;

    void Update()
    {
        if (isPressed)
        {
            // Smoothly accelerate toward forwardSpeed
            rollInput = Mathf.Lerp(rollInput, rollSpeed, rollAcceleration * Time.deltaTime);
        }
        else
        {
            // Smoothly decelerate back to 0
            rollInput = Mathf.Lerp(rollInput, 0f, rollAcceleration * Time.deltaTime);
        }

        // Move the player forward
        Player.transform.Rotate(Vector3.back * rollInput * rollSpeed * Time.deltaTime, Space.Self);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        isPressed = true;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        isPressed = false;
    }
}
real thunder
#

it really is annoying to make a character to properly interact with physics

#

yloing with CharacterController component is good enough for many if not most cases tho

#

which is not obeying physics but kidna interact with it

celest depot
hardy wing
sour fulcrum
hardy wing
#

That's why I'm currently rolling with Rigidbody2D with no gravity and frozen roztation.

real thunder
#

not sure if there is other choice

#

any issues?

sour fulcrum
#

at that point it's only really physics in regards to referencing unity's "physics" system. most of what you do is gonna be closer to smoke and mirrors than stuff comparable to real physics

hardy wing
sour fulcrum
#

oh sure, im pointing this out so you might have a better idea of what to specifically look for

sour fulcrum
#

interactive game to showcase what goes into a standard 2d controller + source code accessible for nity grity

hardy wing
#

That looks cool, will look into it, thanks NODDERS

sour fulcrum
#

googling/asking about 2d character controllers will get you further than how your initial question was phrased

#

best of luck

real thunder
#

I wonder if anyone ever found a code (if it's mathematically reasonable even) to have a Quaternion.SmoothDamp with a limiter and at the same time using spherical motion (like if I get it right if you go with Eulers the path would be not ideal)

#

trying to figure that out lead me to.... robotics forums? I am too silly

#

also am I getting it right that in modern animation software interpolation is not spherical so the path inbetween keyframes is not ideal?

hardy wing
#

Or at least is a start that can transition into it.

real thunder
#

are you sure you want a kinematic rigidbody

#

I mean idk how to properly do that

#

I would try to use a frictionless no bounciness no gravity non-kinematic rigidbody

hardy wing
#

Speaking of which, is it a good idea to do the frictionless thing as the default material or assign it separately for each? Feels a lot more predictable if everything has no friction from the get-go.

real thunder
#

slopes... you just check the angle of normal below you and slide (FSM of movement went from full control to something like sliding in a manner you like) if it's too bad

#

I mean that's what I would do

#

also to move along slopes without slowing down I project movement force onto normal

#

might be terrible for complex rough terrain

real thunder
#

I suspect you need some objects with zero fricion

#

and everything else having it

#

friction combine mode minimum works alright

#

so some things are slippery and controlled by the world while some ain't

hardy wing
#

I think my character stuck to walls too much when jumping against it which I solved by making the player AND the wall have no friction

#

So I feel like the default being no friction would be better so I adjust it if I need some things to be stickier

real thunder
#

what's the difference between average and mean 🤔

hardy wing
#

i have no idea KEKW

errant breach
#

Hello !

Im trying to get the healthbar. UI_healthBar, but for some reason, unity wont let me reference it, instead recommending that is use Ai_healthBar that simply exist nowhere in my program.

Do you know why such a issue happen ? Thanks !

teal viper
#

Or struct.

real thunder
errant breach
#

always thought it only used the script's name 😅, still learning i guess. Thank you !

teal viper
#

Script name is just the file name. It doesn't really matter in code.

errant breach
#

Alright, thanks !

fading barn
#

how do i send code blocks

#

or can i send screenshots

#

private void Start()
{
StartPosition = transform.position;
}
private void Reset()
{
if(ResetAction.IsPressed())
{
Debug.Log("Reset !");
transform.position = StartPosition;
}
}

silk night
silk night
#

also you want WasPressedThisFrame instead of IsPressed or it will fire every frame as long as you hold down your ResetAction key

fading barn
#
    {
        // Ground Check
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);

        MyInput();
        SpeedControl();
        CheckForWall();
        StateHandler();

        // Handle Drag
        if (grounded && !isDashing) rb.linearDamping = groundDrag;
        else rb.linearDamping = 0;

        // Dash Cooldown
        if (dashCooldownTimer > 0) dashCooldownTimer -= Time.deltaTime;

        //RESET Player position to starting positiion
        Reset();
    }
#

i didnt send entire script cause its too long

silk night
#

you can send the entire script on a paste platform

#

!code

radiant voidBOT
silk night
#

So what could still be wrong:

  • ResetAction is not assigned
  • ResetAction has no key assigned
fading barn
silk night
#

oh sorry didnt see the screenshot

fading barn
#

no problem

silk night
#

That you never set the ResetAction in the player script

#

would be the other one

fading barn
sage mirage
#

Hey, guys! I have an issue with a trigger box. For one reason, when my player enters the trigger box, it doesn't execute the code that I have written. I have tried to use debug.log to check if its actually executing the logic, but no. Here is my code:

{
    if (other.CompareTag("Player"))
    {
        lanternLightFlickeringTriggerCollider.enabled = false;
        StartCoroutine(FlickerDelay());
    }
}

private IEnumerator FlickerDelay()
{
    float elapsedTime = 0f;

    while (elapsedTime < flickerDuration)
    {
        lanternLight.intensity = Random.Range(minFlickerIntensity, maxFlickerIntensity);
        elapsedTime += 0.05f;

        yield return new WaitForSeconds(0.05f);
    }
    lanternLight.intensity = 0f;
}```
fading barn
#

i do have assigned it on code

#

tho

silk night
silk night
fading barn
#

yes its a private variable serialized. i have assigned it both in code and in editor

#

and both are same keys

#

r for reset

silk night
fading barn
#

yes

sage mirage
#

Its by default with a value of 2 that I have

#

even though I have declared the variables for min and max, as well as flicker duration

    private float minFlickerIntensity = 0f;
    private float maxFlickerIntensity = 2f;```
fading barn
#

test

silk night
sage mirage
fading barn
#

`it is turning it into a txt file i think its too long

#

322 lines

sage mirage
#

let me send you a video clip

silk night
sage mirage
#

of what is actually happening in depth

silk night
fading barn
silk night
fading barn
#

everything else is working correctly

#

in the code

silk night
#

("<Keyboard/r>");

#

the R goes outside the <>

fading barn
#

oh

#

let me see whether it works now

#

why dont strings give compiler errors

silk night
#

because you are not supposed to compose an input asset like that usually 😄

#

you are better of actually creating an InputActionAsset and assigning that to the player

fading barn
#

so it still dont work

silk night
#

you are also missing the inputactiontype button

fading barn
silk night
#

for the reset action

silk night
fading barn
#

found the culprit i think

#

no still not working

sage mirage
#

Hey! I spread out like almost everywhere debug. log and what I have noticed is that, the lantern intensity is actually changing for 2 seconds as expected but I dont see it change in the inspector and visually at all XD

silk night
silk night
sage mirage
#

you know maybe because I am using animations at one place for my lantern light?? Maybe animation actually affects how it works, when player enters the trigger box. Oh, I think thats the reason bro.

#

Because I have an idle animation for my light

silk night
#

if you are animating the intensity value it would override it, yes

sage mirage
#

which keeps my light at 2 by default

silk night
#

even if you are not changing it, but having a keyframe set it to 2 would block external changes

#

though that should be easy to fix, you can manually delete the keyframes of intensity from the animation

sage mirage
#

So probably I am going to create this flickering effect via code like I did and yes I am going to delete the keyframes and the animation for the flickering effect.

errant breach
#

Hey guys !
I got the error NullReferenceException: Object reference not set to an instance of an object
When i double click on the error, it brings me nowhere. I checked : Both my players and my enemy has all their option correct.
Do you know what it could mean ?

⚠️ the error is displayed even when i dont start up the game

#

As for the code, here is it :

ivory bobcat
errant breach
#

😅 thank !

sage mirage
#

Hey, guys! Can somebody explain please, what yield return null does actually? I was just wondering, in which cases do I have to use yield return null?

#

I have heard it waits for the next frame to proceed but cant understand the use case of it.

#

When and why to use it?

midnight plover
sage mirage
wintry quarry
sage mirage
#

Yes but why to wait that one frame?

wintry quarry
#

For example if you want to do something every frame in a coroutine

#

You could put it in a loop

sage mirage
#

something is happening internally in the memory or what exactly?

wintry quarry
#

Not sure what that question means

midnight plover
keen dew
#

Surely you've used Update a lot? Update does something once every frame. If you want to do that same thing in a coroutine, you can do it with a loop and yield return null

midnight plover
wintry quarry
sage mirage
wintry quarry
#

It's literally just waiting one frame it's not that deep. There are infinite reasons you might want to do that.

midnight plover
sage mirage
#

so instead of seconds its frame right thats the difference from yield return new waitforseonds?

wintry quarry
#

Yes

sage mirage
#

its only one frame

#

or more than one?

wintry quarry
#

One frame...

midnight plover
sage mirage
wintry quarry
#

Whenever you want to wait a frame in a coroutine.

sage mirage
#

lets say a light flickering

#

it can be used for it?

wintry quarry
#

It can be but probably not

sage mirage
#

and why

wintry quarry
#

That's likely more time based

#

Although you may still use it there and set the brightness of a light based on an animation curve

#

So yes it could be used there

#

The most common thing would be smoothly animating the position of an object over time. To do that you need to set the object position once per frame

rich adder
real thunder
#

seek for different homing missle approaches lead me to some github and stuff and...
am I not getting something or this code shouldn't work?

void FixedUpdate(){
        
        float navigationTime = (target.position - transform.position).magnitude / speed;
        Vector3 los = (target.position + targetRb.velocity * navigationTime) - transform.position;

        float angle = Vector3.Angle(rb.velocity, los);
        Vector3 adjustment = pValue * angle * los.normalized;

        rb.velocity = rb.velocity.normalized * speed;
        var target_rotation = Quaternion.LookRotation(adjustment);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, target_rotation, turnRate * Time.deltaTime); 

        rb.velocity = transform.forward * speed;
    }

like, LookRotation only care about a Vector direction, am I getting it right?
pValue presumably meant to adjust leading

#

I mean the code does work... kinda.... not sure that leading works

errant breach
#

Hello !

I want the player to shoot, and i want to pass the projectileSpeed value to the projectile (with various other values). The player has different shoot so i cant really ignore that. But i have this error, do you please know how i can fix it please ? Thanks !

teal viper
real thunder
#

Trying to read the writer's mind, I suppose the plan was to use

Vector3 adjustment = Quaternion.AngleAxis(pValue * angle, Vector3.Cross(los, rb.velocity)) * los.normalized
rich adder
naive pawn
real thunder
#

you can instantiate something as a MonoBehaviour instead of GameObject?

polar acorn
#

Yes

real thunder
#

I was getting this component for nothing all this time

polar acorn
#

Yes

naive pawn
#

a lot of the time you generally don't need to/shouldn't use GameObject as a serialized reference or for passing around

#

since you generally care more about components than gameobjects

shrewd sluice
#

Hi need help with a couple of things...

naive pawn
shrewd sluice
#

Im pretty sure I can make the. Ui with udon, but cards in a 3d plain field with shuffling is kinda difficult and can't find any videos or assets to help with it x.x

#

So far I have been using udon unity ._.) because it's for vrchat

polar acorn
#

!vrchat

radiant voidBOT
shrewd sluice
#

And quest version

shrewd sluice
#

Idk why

#

Still it's unity. So it should work anywas

#

Udon is just an, hehe, addon

polar acorn
#

You're probably not going to find much help with their SDK here.

grand snow
#

Probably not but the question asked is super vague anyway

#

God knows what happens in the vr chat server

naive pawn
#

the people who are able and willing to help with vrchat would be in the vrchat server shrugsinjapanese

real thunder
#

I mean I can also start asking guides for Unity games here in that regard

#

what question you got anyway

#

"cards in a 3d plain field with shuffling is kinda difficult" like... how does that relate to Unity

#

"Udon is a programming language1 for VRChat worlds. Scripts can interact with scene objects, players, synced networked variables, and more. Udon makes your world come to life!" ugh welp yeah you are out of luck

#

asking about it here is about as useful as asking guides for a random Unity game

polar acorn
# shrewd sluice But it's unity no?

People here don't know what is and is not possible in VRChat. You can ask your question but if you get an answer you can't use we can't really do anything about that.

#

This is why you should ask it in the Udon section of the VRChat server. They're familiar with the restrictions of the language and can actually answer you

shrewd sluice
#

Like literally the only thing I typed in the udon discord was some help with stuff and fell asleep, then bam banned like wth

polar acorn
#

That's something you'd need to ask them

real thunder
shrewd sluice
real thunder
#

no, you can do that

#

besides as I checked they shove "read rules" as one of non skippable things on joining

hushed canyon
#

Hey guys. I'm trying to make a 2D game like Super Mario but its not working out great. Right now I have the Movement set up, an Inventory but not the actions to get collected items into it, and thats where I'm stuck, I followed a video to help me make scripts so I could grab items but Its not working. The item just rolls away. And if I make it kinetic (so it doesnt move) I can literally stand on it like an object and it never gets picked up by me. Also tried activating Boxcollider2D --> IsTrigger ON but then it fell through the ground.
This is the video: https://www.youtube.com/watch?v=e7-EJd5dQgQ
Please Pm me if you could help. Id be reallllly greatful. This is for a school project.

naive pawn
naive pawn
errant breach
#

Hello ! My game is crashing because one canva (prefab) doesnt have the camera. But i cant drag and drop the camera to the prefab. (because it's not on the list)

I tried putting one prefab and the scene, setting putting the camera and then Apply changes (overrides) but the "camera" field is still empty. Same if i try to create a new prefab with the camera put...

How can i avoid this problem please ?

hushed canyon
naive pawn
naive pawn
#

it rolling away just sounds like you're walking into it

hushed canyon
hushed canyon
naive pawn
#

so remove it from the world when you pick it up?

#

im confused what the issue is here

#

is the issue that the object is solid?

#

or that it's simulated by physics?

hushed canyon
#

Basically when I toch the object It needs to get "picked up" and dissapear, and later go in my inventory that I set up but I'm not that far yet. Anyways, when I touch the object it just slides/rolls away and doesnt get picked up or destroyed.

hushed canyon
hushed canyon
naive pawn
errant breach
naive pawn
hushed canyon
rough granite
#

Only one object in the collision process needs one and if the player has one the object wouldn't

#

Or if the player doesnt have one for whatever reason give it one but make it a kinematic/static (say kinematic cause i dont remember if static has collision detection)

hushed canyon
rough granite
#

You just said you didnt want it to move, bruh

hushed canyon
#

Yeah, but It still needs to be picked up and when its picked up destroyed

rough granite
#

Is the handling of position when being picked up done through code? Or from collision?

hushed canyon
#

And the InventoryManager:

#

I put the "Item" code into the item I wanted to "collect"

rough granite
#

Neither of these have anything about moving when picked up ~_~

hushed canyon
rough granite
#

Right im not watching a video but that isnt my problem you talked about how not having a rigidbody makes it so when you go to pick it up it doesnt get physically picked up but neither of the two codes you have; have anything about controllering it's position when picked up

hushed canyon
#

Oh alright, thanks for trying to help tho!

rough granite
#

I mean you are the one not giving enough information

#

One minute you are telling me you dont want something to move then the next you are

hushed canyon
hushed canyon
#

Like the coins in Mario Bros

rough granite
#

Then the second thing i gave the first time should work

#

Add the rigidbody back but make it kinematic

hushed canyon
#

Oh alrightttt!! thanks!!

stoic sage
#

Did a code without just following a tutorial
Feels good UnityChanThumbsUp

brazen river
#

Hi

sage mirage
#

My childhood nightmare is here XD

#

Hello btw

brazen river
#

I'm trying to crack the Granny Legacy Il2cpp

sage mirage
#

You can player granny in your phone all of them

#

1, 2 and 3

brazen river
#

Unofficials

sage mirage
#

They are paid only on steam

#

no the original

#

from DVopers

polar acorn
brazen river
#

1 ,2and 3 are old

sage mirage
#

which one?

#

do you want?

#

Legacy I dont know it

brazen river
#

Well the Granny 2 is better than all

sage mirage
#

and third

#

sorry

#

I really want to contact the developers of the game

naive pawn
#

uhh this seems kinda off-topic...

sage mirage
#

probably thats what I am going to do cuz I would like to collaborate with them

polar acorn
#

Also this is not a social server, if you want to talk about the games take it to DMs

brazen river
sage mirage
#

sorry guys it was his pfp

#

ok send me DM

supple flume
#

how can i make my object face another object
when i try to use the LookAt method x and y are the only modified rotaions and it causes it to disappear

naive pawn
#

is this in 2d or something?

supple flume
#

2d

#

ik why it disappears

#

idk how to fix it

frail hawk
#

it disappers because it use the forward axis which is z in 2d

naive pawn
#

LookAt makes the forward vector point that direction, but you need the forward vector to be perpendicular to the camera in 2d

naive pawn
#

just don't use LookAt

#

change the up/right vector of the transform instead

#

provide it a direction vector

naive pawn
supple flume
naive pawn
#

transform.up = newDirection

supple flume
frail hawk
#

to

supple flume
#

transform.up = new Vector2(center.position.x,center.position.y);
this line of code is not working

frail hawk
#

what is the error?

supple flume
#

transform.up = (transform.position - center.position);
This worked for me
what was the problem is...
i was chaning position after rotating

supple flume
#

using base square so didnt notice

naive pawn
supple flume
#

quick question
for a towerdefense
do yall recommend Rigidbody movement or vector movement
performance wise

frail hawk
#

if you want proper collision detection and physics such as gravity etc, you´d have to use a rb

ivory bobcat
supple flume
ivory bobcat
#

Ah, teleporting using the Transform component. If you're planning to roll a ball or fly a rocket, RB would simulate those pretty well. If you're only needing gravity and some complex or strict movement system, you could opt for a kinematic rb and implement the moving yourself with the kinematic method.

polar acorn
supple flume
polar acorn
#

Well, do you want physics or teleportation in a straight line?

verbal dome
#

If you need units to push each other then you probably want to use a dynamic rigidbody

#

But for a tower defense I'm not sure if that's needed

supple flume
#

i have a question
lets say there are lots of objects and i want to print the name of the closest one within a certain range
i thought of making a list and putting all the objects within that range and compare who is the closest to print the name of it
is this the proper approuch or is there a simpler method

cunning rapids
#

I'd say the simplest is just to compare the magnitudes of the distance vector for these objects

supple flume
#

and how can i keep track of them?

cunning rapids
#

Wdym "keep track of them"?

supple flume
#

the magnitude of all the objects within that range

uncut kayak
#

I get the Error Message: MissingMethodException: Method 'PlayerController.OnMove' not found. when Trying to use Unity's New Inputs System

#

this is how I set up my code:

using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
    public float movementSpeed = 10.5f;
    public Rigidbody2D rb;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnMove(InputAction.CallbackContext PLEASE)
    {
        Debug.Log(PLEASE.ToString());
    }
}
wintry quarry
cunning rapids
supple flume
cunning rapids
cunning rapids
uncut kayak
supple flume
#

How do i return the object with this??

cunning rapids
supple flume
#

I mean the collider2d
how can i use that to return the object

#

i just refer it o it as var name.gameobject?

cunning rapids
#

The circle itself is a collider. Then just use collidername.CompareTag("Tag name")

supple flume
#

enemy isnt getting assigned reason why?

cunning rapids
#

For example

Collider2D circ = Physics2D.OverlapCircle(transform.position, radius);
if (circ != null && circ.CompareTag("Object") { /*do something*/ }
#

Then assign the tag "Object" to the objects you wanna track

slender nymph
supple flume
#

but i specified it to be layer 6

cunning rapids
#

Tags are better than layer imo anyway

slender nymph
#

no, you passed 6 as the layer mask, which is 0b110 in binary, or a mask for layers 2 and 3

supple flume
#

which is a lyaer i made

cunning rapids
#

It's faster and cleaner

#

Depends on the use case obv

slender nymph
cunning rapids
#

Faster to code (my example), ergo its cleaner

#

Rather than passing layermasks for the overlapcircle

slender nymph
#

it's literally more clutter, and it is easier to just expose a LayerMask variable to the inspector and pass that to the overlap circle call than it is to use a separate tag check

verbal dome
supple flume
slender nymph
supple flume
#

well i made a var for layermask and assigned it manually in editor and works

cunning rapids
slender nymph
#

overlapcircle is returning a single one though

cunning rapids
#

It's the same with layermasks

slender nymph
verbal dome
supple flume
cunning rapids
#

No denying that it can be useful but idk if that's necessary here

slender nymph
#

because you want to only find specific objects so those objects should be on a specific layer

supple flume
#

so if i give it 9
ill get the first and the fourth layer? am i correct

cunning rapids
slender nymph
#

so you create extra work for not only yourself but the runtime. and you somehow think that is cleaner and faster?

cunning rapids
#

It's faster to write and unless you have a shit ton of stuff the performance gain is negligible

supple flume
#

is it possible to remove a value from a list? cause in most lists and programming languages they dont allow deletion of a value

slender nymph
#

if it is a list and not an array then yes

polar acorn
# cunning rapids It's the same with layermasks

It's not. Tags are hashed strings which are compared for equality. Layers are bitmasks done with boolean operators and thus require only a single CPU cycle to compare instead of multiple function calls

polar acorn
slender nymph
supple flume
slender nymph
#

read the page i linked about how bitmasks work to understand them

polar acorn
#

It will get you layer 0 and layer 3

supple flume
#

so what i said is partially correct

slender nymph
cunning rapids
#

Are we not using tags?

#

If not then I'm wrong

polar acorn
#

Why use tags when you can use a layer mask

slender nymph
#

my whole point here was that comparing tags is in no way faster or cleaner than just filtering the query using a layermask first

cunning rapids
#

Fair enough

I thought the setup you were suggesting was

Assign tags for objects --> then assign the layermask for the object --> filter layermask --> comapre tags

#

My bad

slender nymph
#

nobody said "use binary assignment" whatever the hell that is supposed to mean. we explicitly said to expose a LayerMask variable to the inspector and use that

uncut kayak
polar acorn
wintry quarry
supple flume
#

quick question
when i remove a value from the list and will the ones above it go down by 1??

wintry quarry
supple flume
#

thank you

slender nymph
#

that is why List.Remove is an O(n) operation and the larger the list, the slower the operation will be when removing things nearer index 0. though for the most part you won't really have to worry about that so much

cunning rapids
#

Just out of curiousity is there a way to reduce the time complexity

slender nymph
#

of List.Remove? no. Lists are just arrays where things move around sometimes (notably when you insertat or remove)

cunning rapids
#

I meant more generally if you have a set and you wanna remove an element from said set

slender nymph
#

anything after the InsertAt or Remove(At) call needs to be shifted up/down appropriately which is where that time complexity comes from

cunning rapids
polar acorn
wintry quarry
#

But often with a list you care about the ordering

wintry quarry
#

but if you care about ordering and don't want any gaps, you can't help it

#

another approach is basically nulling the element out instead of removing it - but then the index of the list elements gets weird and you have gaps you need to skip over when iterating

#

so.. .everything is a tradeoff

cunning rapids
#

O(n) isn't really a big deal anyway to be fair unless you have TONS of objects, in which case other optimizations should be at play regardless

slender nymph
#

this is why there are many different types of collections and using the right one for what you are doing is important.
if you only ever care about what was most recently put in, you should use a Stack, if you only care about the last object put in then a Queue, if you want something you can index into and resize as needed a List, and a fixed size with indexing an Array, etc

supple flume
#

is there away to change the values of a vectorn into a whole number??

cunning rapids
supple flume
#

so i can compare which is bigger

slender nymph
#

why do you need whole numbers for that? you do know the comparison operators work for floats, right?

wintry quarry
#

that's the "length" of the vector

naive pawn
wintry quarry
#

otherwise it's not clear to me what you mean by "which one is bigger"

supple flume
wintry quarry
naive pawn
supple flume
wintry quarry
#

and if you just want to know which one is better - you should compare sqrMagnitude

slender nymph
supple flume
wintry quarry
naive pawn
#

then no, it's not correct

cunning rapids
#

Then use the distance method instead

wintry quarry
#

what you're doing right now is not right, no

slender nymph
naive pawn
#

a - c > b - c is the same as a > b. you're just comparing the magnitudes there, so just whichever is farthest from the origin

#

subtracting position vectors essentially changes the origin point

cunning rapids
supple flume
#

what abou tthis

wintry quarry
#

but it's correct

naive pawn
#

i feel like a few sqrts is worth the readability here tbh, unless this is a hot codepath

slender nymph
#

pretty sure it's in a loop in update so pretty hot

supple flume
naive pawn
#

ah. just got here, mb.

wintry quarry
# supple flume how so

something like:

float closestDistance = float.PositiveInfinity;
Transform closestEnemy = null;

foreach (Transform enemy in enemies) {
  float distance = Vector3.Distance(enemy.transform.position, transform.position);
  if (distance < closestDistance) {
    closestEnemy = enemy;
    closestDistance = distance;
  }
}```
supple flume
#

in a loop

wintry quarry
naive pawn
#

ah, i see

wintry quarry
#

having very long lines with lots of functions etc is hard to read and often less performant because you tend to not be using intermediate variables

naive pawn
#

i was missing a lot of context lmao

verbal dome
#

I might add that you likely don't want to update the target every frame anyway. It's unnatural, chaotic and can be jittery if boucning between targets
For example doing it a few times in a second usually works

supple flume
slender nymph
#

fwiw though this can probably be moved to FixedUpdate since it's not like physics is updating between FixedUpdate calls anyway, and this seems to be a TD game so the towers probably aren't moving their positions either, so the OverlapCircle call would be returning the same information for however many frames between FixedUpdates anyway

supple flume
#

cause i just realised this doent work cause it will only loop once

wintry quarry
naive pawn
wintry quarry
#

this enemies.Add(...overlapcircle..) thing you're doing looks really fishy to me

#

and yeah where does size come from here?

supple flume
# naive pawn why would it only loop once? is `size` just a constant `1`
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Raduis : MonoBehaviour
{
    public Vector2 vector;
    public Transform center;

    
    public LayerMask mask;
    public float size;

    public Collider2D closest;

    public List<Collider2D> enemies = new List<Collider2D>();

    public float rot;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
        //if (Input.GetKeyDown(KeyCode.Space))
        //{   
            //vector = Random.insideUnitCircle.normalized * 2f;
            //Debug.Log(vector);
            ////transform.position = vector;
            
            
        //}
        if (!enemies[0])
        {
            closest = Physics2D.OverlapCircle(transform.position,2,mask,0,6);
            enemies.Add(closest);
        }

        
        
        if (enemies[0])
        {
            enemies.Add(Physics2D.OverlapCircle(transform.position,2,mask,0,6));
            for(int i =0; i < size; i++)
            {
                if(Vector2.Distance(closest.transform.position,transform.position) > Vector2.Distance(enemies[i].transform.position, transform.position))
                {
                    closest = enemies[i];
                }
            }
            
            
        }

        
    }
}
#

this is the code

cunning rapids
#

Don't use lists here. OverlapCircle returns colliders. filter the layermask(s)

slender nymph
#

should be passing the list to OverlapCircle so it can fill it in with all of the nearby results

wintry quarry
#

use the override that dumps the results in the list

supple flume
slender nymph
supple flume
slender nymph
naive pawn
#

why is size a float

supple flume
wintry quarry
#

you should use the version of OverlapCircle that dumps the results directly in your list

cunning rapids
wintry quarry
polar acorn
slender nymph
cunning rapids
#

I see

supple flume
#

and !enemies wont have an assigned value at first so the first time it does it will assign it to closest as well

slender nymph
# cunning rapids I see

using the overload of OverlapCircle that populates an existing collection with the results means that there are fewer allocations, and with this happening in Update it will put far less pressure on the garbage collector

polar acorn
#

The body of this if statement literally will not run

cunning rapids
supple flume
supple flume
slender nymph
polar acorn
supple flume
slender nymph
#

also this overload of OverlapCircle will return the number of objects it found so use that rather than the count of the list

#

if you just blindly loop through the list populated by OverlapCircle you're going to run into invalid results because it doesn't clear the list, it just overwrites up to the index it needs to

supple flume
slender nymph
#

you loop through the list up to the index returned by the method call

#

or rather the count returned by the OverlapCircle method call

slender nymph
#

so you know how to use a for loop, right? and you know how to store the return value from a method?

slender nymph
#

so put that knowledge together

supple flume
#

ok before that help with this
if i dont put [] i get an error what should i put in

naive pawn
#

putting in [] also gives an error, so clearly not that

slender nymph
#

stop using enemies.Add there, and i already told you why that happens. and also you get an error when you do put [] there because that's even more wrong

polar acorn
#

It returns an int.

#

You pass it the list.

supple flume
#

i mustve CTRL z it

polar acorn
#

enemies is not a list of ints, so enemies.Add(<thing that returns an int>) is not valid

supple flume
#

yeah works now

slender nymph
#

make sure to actually store the returned int from the OverlapCircle call like we just discussed

naive pawn
#

i mean tbf you don't even really need to use the return with the list overload, you could just foreach over the list

slender nymph
#

doesn't the list not get cleared and just overwritten?

naive pawn
#

...i don't see how those 2 are different

polar acorn
#

If the list is too small it will be resized. If the list is too big, it will not overwrite the unused values

slender nymph
polar acorn
#

So, you do need to use the int result, otherwise you'll have garbage data at the end of the list

naive pawn
#

ah, i see what you mean. you could just clear the list beforehand though, no?

#

that's what i usually see, i feel like

polar acorn
#

Yes, but that'd defeat the purpose of optimizing the clear out

naive pawn
#

i think i lost the plot. aight

polar acorn
#

Clear isn't free, it causes garbage collection. By not doing the clear, it prevents needing GC

naive pawn
#

i don't think that's true

supple flume
#

enemes is no longe rgetting a value

slender nymph
supple flume
#

in editor

slender nymph
#

well, any GC other than releasing references to destroyed objects, i mean

slender nymph
# supple flume in editor

any particular reason you're using depth for that? and are the objects you are trying to find within that range?

polar acorn
# supple flume

Try logging the count after this call. If it's still empty, then there's nothing in the overlap range

naive pawn
#

the 2 is radius

supple flume
slender nymph
naive pawn
#

ah, mb. i read that as a layermask in the code

polar acorn
naive pawn
supple flume
slender nymph
#

that doesn't mean they are within that range of depth you are checking. depth isn't distance from the object, it is distance along the z axis

supple flume
#

i disabled depth

#

i did depth just to make sure its missing wasnt the problem

#

i disabled it again

slender nymph
#

then show the actual object(s)

#

and ideally the entire snippet of code

supple flume
#
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Raduis : MonoBehaviour
{

    public Transform center;

    public float size;

    public Collider2D closest;
    public ContactFilter2D filter;

    public List<Collider2D> enemies = new List<Collider2D>();


    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
        //if (Input.GetKeyDown(KeyCode.Space))
        //{   
            //vector = Random.insideUnitCircle.normalized * 2f;
            //Debug.Log(vector);
            ////transform.position = vector;
            
            
        //}

        Physics2D.OverlapCircle(transform.position,1,filter,enemies);

    }
}

the code

#

the enemy object

slender nymph
#

you have IsTrigger there, but Use Triggers is unselected in the ContactFilter2D

supple flume
#

i enabled it too

#

dawg

#

im going insane

polar acorn
supple flume
#

when i enabled it in filter it did

#

im Schizophrenic as hell

slender nymph
#

so it's working now?

supple flume
supple flume
# slender nymph so it's working now?

so i did some tweaking

    {
        enemies.Clear();

        Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);

        if (enemies.Count == 0)
        {
            closest = null;
            return;
        }

        closest = enemies[0];
        float closestDistance = Vector2.Distance(transform.position, closest.transform.position);

        for (int i = 1; i < enemies.Count; i++)
        {
            float distance = Vector2.Distance(transform.position, enemies[i].transform.position);

            if (distance < closestDistance)
            {
                closestDistance = distance;
                closest = enemies[i];
            }
        }

        if (closest != null)
        {
            Vector2 dir = closest.transform.position - transform.position;

            if (dir.sqrMagnitude > 0.001f)
                transform.up = dir;
        }
    }```
you mentioned erlier that i should put the update stuff in fixedUpdate should i do it now?
and will it impact performance if i dont
slender nymph
#

there likely won't be much performance impact compared to doing this in FixedUpdate, but there will be some benefit, even if it is fairly minor. if you end up with a lot of objects doing this though the benefit to making that change will increase.
Like i said before, physics objects only update on FixedUpdate frames so all those frames in between you are just getting the exact same results as the last FixedUpdate frame

supple flume
#

so i dont really need to change anything?

slender nymph
#

not really, but there will be some benefit if you do. literally the only change would be prepending "Fixed" to the word "Update"

supple flume
slender nymph
#

well no, that was my whole point before about using the returned int from the method. but clearing the list like you're doing does that anyway

potent portal
#

i dont know if this has already been answered but why is vscode being deprecated and what does this mean?

wintry quarry
slender nymph
#

-Code

potent portal
wintry quarry
potent portal
#

im only finding these 3

wintry quarry
#

yep

wintry quarry
#

the third one

potent portal
#

sorry my bad

#

i got a bit confused when you say "Visual Studio Code" package

wintry quarry
#

yeah my bad

potent portal
#

thanks for explaining

upper loom
#

what code is needed for stats increase per level up?

wintry quarry
upper loom
#

like for example when an enemy object levels up how to increase the stats like HP DMG and stuff. do i do it manually or there is some sort of code that automatically multiplies it?

wintry quarry
#

some games use linear growth. Some use polynomial growth. Some use exponential growth. Some even use logarithmic growth

#

Obviously you would need to write the code to apply whatever growth function you want.

#

And yes some games use manually created piecewise functions or tables, where every value is manually defined.

upper loom
#

thanks for the explaining i will look them upUnityChanThumbsUp

upper loom
polar acorn
#

+ is generally how you add numbers

#

which is a way to increase something

upper loom
#

same ways as i++?

cosmic quail
upper loom
#

i was referring to the i++ in the ''for'' code

slender nymph
#

and that is exactly the same as i = i + 1;

solar hill
#

its the same i++

polar acorn
solar hill
#

it can even be awesomeVariableName++

#

does the same thing

upper loom
#

uh. i still got things to learn huh

hexed terrace
#

we never stop learning

grand snow
#

wait till you learn about ++foo and bar++

upper loom
#

i recently learned that i can type 2+ names in a single primitive type and it will work just fine instead of 1 name for every primitive type

solar hill
#

you mean like "int b, a" ?

#

you could do that but i honestly dont see any point in keeping it on the same field

#

you typically want them to be seperate for other reasons

hexed terrace
solar hill
upper loom
upper loom
solar hill
#

nobody is ever done learning

sour fulcrum
#

you stop learning when your dead

solar hill
#

i was about to say something equally macabre

dreamy lance
#

bit of a complicated question but:
im working on a car chase game with some friends and im in charge of making the cop ai for the game. ive tried using the navmesh/nave mesh agent to make them fallow the player and that works.. kinda... it doesnt allow me to apply our custom car physics the the cars. does anyone have an rescources or anything i can use the find an alternitave ?

grand snow
sour fulcrum
#

the beginner skill check is honestly learning how to learn

polar acorn
sour fulcrum
dreamy lance
slender nymph
upper loom
hexed terrace
solar hill
#

i distinctly remember it being on the asset store along side the pro one

slender nymph
#

i think you have to get it from the dev's website but should still be available

hexed terrace
#

I dunno, I've got the paid version.. which I have no idea when I got, possibly in a humble bundle pack? possibly forever ago

solar hill
slender nymph
#

oh looks like he stopped updating the free version, hasn't been updated since 2021. the paid version also just got a new major release recently (feb 2024 is not recently lol)

hexed terrace
upper loom
#

out of context but what is you guy's favorite code? mine is IF because it can be use almost everywhere

sour fulcrum
#

shame it's not easily touchable

hexed terrace
#

I think baking the navmesh at runtime is rather expensive and time consuming too? Whereas with A* it isn't

sour fulcrum
#

yeah but i imagine that just comes with the territory of reading and processing mesh data right

hexed terrace
#

I haven't touched either in ages.. and i tend not to look into the workings of plugins beyond how to use 'em

sour fulcrum
#

super fair

#

spent a fair bit of time playing with navmesh stuff for lethal mods experimenting with sampling data in general and potential ways of optimising bakes

ocean inlet
#

would someone be able to help with this?

im trying to make controller work on a pause menu but its not working. I was following a tutorial and this error happened

slender nymph
#

use the correct type name

polar acorn
ocean inlet
slender nymph
#

then you didn't follow it 100%

solar hill
#

and show us what the Tutorial has for the InputManager script

subtle mulch
slender nymph
#

I have a sneaking suspicion that we are looking at what the tutorial has for the InputManager script 😉
or at least, with a single word difference

ocean inlet
#

I think I pulled a stupid

hexed terrace
ocean inlet
#

and that I was supposed to name the thing after the code itself

#

I didnt realize it mb

slender nymph
#

you should start by learning the basics of the language, so that you'll realize that what you are referring to as "the code itself" is the class, which is a type.

polar acorn
#
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 200
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2026-02-25

200 party_parrotparty_parrotparty_parrot

ocean inlet
#

ok

vagrant leaf
#

helloo

#

where do I start getting back into coding for unity, I haven't worked on it in months

slender nymph
#

!learn or the pins in this channel

radiant voidBOT
upper loom
pallid wasp
#

Hello, everyone

#

I am a junior Unity developer

#

#

But I have been trying hard

subtle mulch
pallid wasp
#

Cuz this is "code-beginner" channel

subtle mulch
#

that is not code

solar hill
#

also please use id:browse to find out what each channel is really for

pallid wasp
zenith gale
shrewd sluice
#

how do i make this material only render to the back or face

#

trying to make a card template sooo

ivory bobcat
shrewd sluice
#

oh

spring hamlet
#

what happens when you have a class and an inheritor that both derive from an interface, and you try to retrieve an instance of that interface with Get/TryGetComponent, and call the interface's methods? does it return the "topmost" instance of the interface or do something else?

ivory bobcat
#

You would get whatever component you've substituted type T with relative to TryGetComponent.

spring hamlet
# ivory bobcat Can you show an example?
public interface ISpawnListener
{
  public void OnSpawn();
}

public class EnemyController : MonoBehaviour, ISpawnListener
{
  // ... other stuff
  public void OnSpawn()
  {
    // some initialization
  }
}

public class Enemy : EnemyController, ISpawnListener
{
  // ... more stuff
  public void OnSpawn()
  {
    // more initialization
  }
}

public class Spawner : MonoBehavior
{
  public GameObject Spawn(string obj, Vector3 where)
  {
    // stuff
    spawnedObject.TryGetComponent(out ISpawnListener listener);
    listener.OnSpawn();
  }
}

something like this

ivory bobcat
spring hamlet
#

? you can do that though

slender nymph
spring hamlet
#

I feel like it'd just be easier to have an interface specifically for classes that want to listen for events like being unloaded or spawned

slender nymph
#

what i mean is that Enemy here already inherits the EnemyController's implementation of the interface so just make those methods virtual and override them in Enemy instead of just reimplementing the interface

#
public class EnemyController : MonoBehaviour, ISpawnListener
{
  // ... other stuff
  public virtual void OnSpawn()
  {
    // some initialization
  }
}

public class Enemy : EnemyController
{
  // ... more stuff
  public override void OnSpawn()
  {
    // more initialization
  }
}

just this

ivory bobcat
#

ISpawnListener isn't a component, so you'd simply use EnemyController or Enemy

slender nymph
#

by manually implementing the interface again you're just hiding the base class's methods. doing this allows you to even optionally call the base class's methods, and won't cause issues if you store the instance in a variable of the base class's type

slender nymph
ivory bobcat
sour fulcrum
#

if its not implemented by a component type it wont return anything

#

but any component that does implement it is the type the function is looking for so

supple flume
#

i should put time counters in Update Not fixed Update right

slender nymph
#

it depends, what exactly are you doing

supple flume
slender nymph
#

then unless a difference of 0.02 seconds is too much, it doesn't really matter

supple flume
#

so i can put it in fixed update and keep everything there

supple flume
#

wait no doesnt seem right cause i dont want it to instantly attack

slender nymph
#

I don't personally recommend Invoke, but yes that is an option

#

keep in mind that any timer you use for it doesn't necessarily have to be directly tied to the actual attack. you can even do your timer in Update and just check a variable in FixedUpdate

supple flume
#

so seems a bit realistic like the bullet was already reloaded

#

why isnt this working
and yes delay value is 5 and i do call the function

slender nymph
#

how have you determined it isn't working, also show the full context for it

#

!code

radiant voidBOT
supple flume
#
using System.Collections.Generic;
using UnityEngine;

public class Raduis : MonoBehaviour
{
    public ContactFilter2D filter;
    public List<Collider2D> enemies = new List<Collider2D>();

    public Collider2D closest;

    public float timer=0;
    public float delay=5;
    public bool canshoot;

    void FixedUpdate()
    {
        enemies.Clear();

        Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);

        if (enemies.Count == 0)
        {
            closest = null;
            return;
        }

        closest = enemies[0];
        float closestDistance = Vector2.Distance(transform.position, closest.transform.position);

        for (int i = 1; i < enemies.Count; i++)
        {
            float distance = Vector2.Distance(transform.position, enemies[i].transform.position);

            if (distance < closestDistance)
            {
                closestDistance = distance;
                closest = enemies[i];
            }
        }

        if (closest != null)
        {
            Vector2 dir = closest.transform.position - transform.position;

            if (dir.sqrMagnitude > 0.001f)
                transform.up = dir;
        }

        Shooting();
    }

    void Shooting()
    {
        if (timer < delay)
        {
            timer += Time.deltaTime;
        }
    }
}
sour fulcrum
#

how do you know you are calling it

slender nymph
#

keep in mind that your code doesn't reach that point if no enemies are within range

supple flume
#

Oh shi i totally forgot

supple flume
#
using System.Collections.Generic;
using UnityEngine;

public class Raduis : MonoBehaviour
{
    public ContactFilter2D filter;
    public List<Collider2D> enemies = new List<Collider2D>();

    public Collider2D closest;

    public float timer=0;
    public float delay=5;
    public bool canshoot;

    void FixedUpdate()
    {  
        facingEnemies();
        Shooting();
    }

    void facingEnemies()
    {
        enemies.Clear();

        Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);

        if (enemies.Count == 0)
        {
            closest = null;
            return;
        }

        closest = enemies[0];
        float closestDistance = Vector2.Distance(transform.position, closest.transform.position);

        for (int i = 1; i < enemies.Count; i++)
        {
            float distance = Vector2.Distance(transform.position, enemies[i].transform.position);

            if (distance < closestDistance)
            {
                closestDistance = distance;
                closest = enemies[i];
            }
        }

        if (closest != null)
        {
            Vector2 dir = closest.transform.position - transform.position;

            if (dir.sqrMagnitude > 0.001f)
                transform.up = dir;
        }
    }

    void Shooting()
    {
        if (timer < delay)
        {
            timer += Time.deltaTime;
        }
    }
}

yeah now it works

#

one question when instantiate an object can i decide where it faces?

verbal dome
verbal dome
#

It just makes the game logic non-framerate dependent

#

And for example I know that I never need to tick my AI classes faster than fixedupdate (50 fps)

verbal dome
#

If the game renders at 25 FPS or 150FPS, fixedupdate will still run at 50 FPS which I want for the gameplay logic

#

I guess I'm also futureproofing for networking, from my understanding servers usually tick at a certain rate

supple flume
#

can i collision detect by 2 triggers?

slender nymph
# supple flume can i collision detect by 2 triggers?

triggers don't collide, but if you want a physics message, there is OnTriggerEnter which is the trigger counterpart to OnCollisionEnter. obviously use the 2d version if using 2d, and make sure you've got the correct setup for the message

supple flume
#

is this correct

#

both of the objects are trigger

#

wait i need to do collision.gameobjcet

slender nymph
#

ideally you'd use the CompareTag method rather than string equality for checking the tag, but otherwise yes. also is there a reason that ES is a field rather than just a local variable?

slender nymph
supple flume
slender nymph
#

yes, you can call GetComponent on any component and it will get the component from that component's game object. just like calling it on the component's gameObject property would

slender nymph
#

a field is a variable declared at the object level (directly in the class in this case)

supple flume
#

ohhhh i thought there is no performance issue by making it up there

#

why does the object try to move but keep being stuck?

transform.position += transform.right * speed * Time.deltaTime;```
#

instantiation method

Instantiate(Bullet, shootpoint.position, transform.rotation);
slender nymph
supple flume
#
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class Raduis : MonoBehaviour
{
    public ContactFilter2D filter;
    public List<Collider2D> enemies = new List<Collider2D>();

    public GameObject Bullet;

    public Collider2D closest;

    public Transform shootpoint;
    public float health = 2;

    public float timer=0;
    public float delay=5;
    public bool canshoot;

    void FixedUpdate()
    {  
        facingEnemies();
        Shooting();
        if(health <= 0)
        {
            Debug.Log("YOU LOST");
        }
    }

    void facingEnemies()
    {
        enemies.Clear();

        Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);

        if (enemies.Count == 0)
        {
            closest = null;
            return;
        }

        closest = enemies[0];
        float closestDistance = Vector2.Distance(transform.position, closest.transform.position);

        for (int i = 1; i < enemies.Count; i++)
        {
            float distance = Vector2.Distance(transform.position, enemies[i].transform.position);

            if (distance < closestDistance)
            {
                closestDistance = distance;
                closest = enemies[i];
            }
        }

        if (closest != null)
        {
            Vector2 dir = closest.transform.position - transform.position;

            if (dir.sqrMagnitude > 0.001f)
                transform.up = dir;
        }
        if (canshoot)
        {
            Instantiate(Bullet, shootpoint.position, transform.rotation);
            canshoot = false;
            timer = 0f;
        }
    }

    void Shooting()
    {
        if (timer < delay)
        {
            timer += Time.deltaTime;
        } else canshoot = true;
    }
}```
this is the script where it gets cloned
#
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{

    public float speed;
    private EnemyScript ES;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = transform.up * speed * Time.deltaTime;
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "enemy")
        {
            ES  = collision.gameObject.GetComponent<EnemyScript>();
            ES.health -=1;
        }
    }
}
``` this is the script where it moves
#

forSome reason it spawns in 0,0,0 even tho i assigned shootpoint

snow depot
#

I manually changed the GUID of my only scene in Unity... and now unity doesn't recognize it... is it recoverable???

slender nymph
#

this is a code channel

slender nymph
supple flume
#

and the thing is
it keeps going to 0,0,0

slender nymph
#

how have you confirmed either of those things

supple flume
#

cause the values try to move up but they keep getting reverted to 0

supple flume
slender nymph
#

stop making assumptions based on what you see in the inspector

supple flume
#

i figured out the problem..
transform.position = transform.up * speed * Time.deltaTime;
I SWEAR i saw the + like 5 times

slender nymph
#

you need to verify everything in your code either with logs or breakpoints. the inspector can only render once per frame, things can change more frequently than that

supple flume
slender nymph
#

wdym "and its rendering"?
you also need to be moving using the rigidbody rather than the transform

supple flume
slender nymph
#

because physics messages may not work if you aren't moving the rigidbody. what you're doing now is effectively just teleporting it every frame

supple flume
#

oh will change movement to rigidbody when i done with all the basic ideas i need

#

one question
how different is GameManager

slender nymph
#

i don't understand what you mean by that question. GameManager is not something built in, so the question without context is meaningless

supple flume
#

is it special in anyform

slender nymph
#

just an old quirk of unity, doesn't really mean anything

sour fulcrum
#

the icon is the only thing

slender nymph
#

pretty sure it's been patched out at this point too

supple flume
#

oh lol

supple flume
slender nymph
#

i think it was removed in 6

#

maybe 6.1

slender nymph
supple flume
#

yeah i just found it i dont have it anymore

gaunt cipher
#
    {
        StartCoroutine(UnlockRankBootstrap());
    }

    private IEnumerator UnlockRankBootstrap()
    {
        yield return StartCoroutine(AlignKeyWithLock());
    }

    private IEnumerator AlignKeyWithLock()
    {
        yield return new WaitForSeconds(1.0f);

        UnlockRank(NextRankToUnlock, false);
        NextRankToUnlock--;
    }```
#

I might be missing something, but UnlockNextRank is called from another file. You need to be in a Coroutine to yield return, so this is the only way to get the program to 'halt' and wait for execution. Is there no easier way than StartCoroutine -> yield return another coroutine? It just feels like a lot of scaffolding to get things started

#

I guess you can nest the second IEnumerator inside the first with System.Collections but it still feels excessive

wintry quarry
#

What's the point of UnlockRankBootstrap if it does nothing but yield another coroutine?

#
public void UnlockNextRank() {
   StartCoroutine(AlignKeyWithLock());
}``` would be perfectly valid and do exactly the same thing