#💻┃code-beginner

1 messages · Page 542 of 1

dense bridge
#

Ok so by default this should be colliding... this is a rigidbody2D right ?

tired slate
#

so i should change the layers to default?

dense bridge
#

screen your rb component

tired slate
#

u mean that?

dense bridge
tired slate
#

no, i didnt make it local

dense bridge
#

Try private void OnTriggerStay2D(Collider2D other)
instead of private void OnTriggerEnter2D(Collider2D other)

#

maybe your are moving via transform, so you bypass the physic logic

#

it is just for debugging, if this works you should improve this because on trigger stay will be triggered every frame

tired slate
#

its dont work after change for private void OnTriggerStay2D(Collider2D other)

#

I Mean nothing changed

dense bridge
#

damn... And on console and editor no warnings/errors ?

tired slate
#

yes

#

this is right?

languid spire
#

Your Rigidbody type is Kinematic which means it is ignored by the physics system

tired slate
#

so what i should do?

languid spire
#

change it?

tired slate
#

when i change for dynamic my hero go down and down, but when I set at static it still dont work

languid spire
#

when you change to dynamic and it goes down it means there is nothing beneath it to support it

dense bridge
# languid spire change it?

well i thought rb kinematic still make collisions... >>>Kinematic bodies also affect the motion of other rigidbodies through collisions or joints.
They are just not affected by others. So you are indeed right, the script can't process.

#

Your city have no rigidbody right ? Just a box collider trigger ?

dense bridge
#

Oh ok... So you must make the OnTriggerEnter2D on your city. Try it with the tag of your player.
This way you can keep your player kinematic

tired slate
#

oh, thanks, it work

#

thanks for help and patience

dense bridge
tough tartan
#

Hi so im following this tutorial and am about21 mins in

#

and im getting this error

#

when trying to run the movement

arctic wren
#

Hey, I didn't code for 3 years, and I'm trying to get back into coding. I want help with figuring out why the "If, else" isn't working.

little meteor
arctic wren
little meteor
dense bridge
# tough tartan

Well you should have no mesh agent component on a waypoint, click the error and share the relevant script part

arctic wren
#

nvm, fixed it, there was a semicolon that wasn't supposed to be there. Thank you

tough tartan
#

i am in school so i cant really work on it that much

dense bridge
dense bridge
languid spire
#

I would question why a Waypoint would have a NavMeshAgent component in the first place

dense bridge
#

i think he tried to getcomponent instead of player.getcomponent

hexed terrace
burnt vapor
#

You forgot to post the actual question

#

Also, please use a paste site for your !code

eternal falconBOT
languid spire
#

!code. Use a paste site

eternal falconBOT
unreal basin
#

On it my apologies again

dense bridge
hexed terrace
#

seems like a small thing that they can learn about quickly

#

at the bare minimum cache the get ;p

burnt vapor
#

This is a coding channel, not sure why you ask here

hexed terrace
#

Seems self explanatory too

cerulean bear
#

Okay thanks. But how can I make it so that clone only make one clone

eager spindle
cerulean bear
#

Oh ok thanks

lime pewter
#

Hey all! Just wondering if there is an effective way to determine clicks on canvas elements, potentially similar to a raycast? Currently I am working on a menu system and I'm not sure if I should be creating an "Interactables" list (containing anything that can be clicked) which I loop through to compare distance of each element on click, I assume that there's a wildly more efficient way of doing it. Any ideas would be greatly appreciated!

lime pewter
lime pewter
#

Haha funny timing!

languid spire
night mural
#

yep there are those at well if it makes sense to manage your selection from each object (I don't think that's very often the case in reality)

lime pewter
hallow hound
#

hey every time i change somthing in the script unity takes a whilee reloading stuff, anyone know how can i speed that up?

visual linden
little meteor
hallow hound
hallow hound
#

just changing 1 value it takes a loot

verbal dome
#

It needs to recompile everything in that assembly because other scripts could depend on that "1 value"

visual linden
verbal dome
#

Dont think assembly definitions help much if you have 5 scripts 😄

#

Useful for later for sure

visual linden
#

Missed that part 👀

#

Although, what are the odds they "have 5 scripts" and forget to mention 20-or-so asset packs 😅

verbal dome
#

Yeah

hallow hound
#

i only have those scripts, one texture and one material 😆

verbal dome
#

Speaking of, it doesnt only recompile scripts, it could also be running OnEnable/Awake on some assets etc.

naive pawn
#

is it in the global prefs or project settings?

naive pawn
#

ah, i was searching for "domain" and "reload".

#

thanks!

visual linden
#

Ah yeah, my bad 😅 Forgot the exact name of it

vocal wharf
#

In my open world car drifting game I added a script to change the color of the car by clicking UI buttons. I have red, orange, yellow, green, blue, purple, white, and black color options. Literally every single one works except for the orange color option. It's coded just like all the others and the button is set to activate the correct method, but every time I click the orange button it makes the car yellow, the same exact shade as my yellow color option. Any ideas why only the orange one isn't working?

public class CarColor : MonoBehaviour
{
    public Material carMaterial;
    public AudioSource audioSource;
    void Start()
    {
        carMaterial.color = new Color(0, 0, 0);
    }
    public void carColorRed()
    {
        carMaterial.color = new Color(255, 0, 0);
        audioSource.Play();
    }
    public void carColorOrange()
    {
        carMaterial.color = new Color(255, 128, 0);
        audioSource.Play();
    }
    public void carColorYellow()
    {
        carMaterial.color = new Color(255, 255, 0);
        audioSource.Play();
    }
    public void carColorGreen()
    {
        carMaterial.color = new Color(0, 255, 0);
        audioSource.Play();
    }
    public void carColorBlue()
    {
        carMaterial.color = new Color(0, 0, 255);
        audioSource.Play();
    }
    public void carColorPurple()
    {
        carMaterial.color = new Color(255, 0, 255);
        audioSource.Play();
    }
    public void carColorWhite()
    {
        carMaterial.color = new Color(255, 255, 255);
        audioSource.Play();
    }
    public void carColorBlack()
    {
        carMaterial.color = new Color(0, 0, 0);
        audioSource.Play();
    }
}
naive pawn
#

that could be a lot of things
did you check all the links throughout?

vocal wharf
#

wdym by links

naive pawn
#

make sure you've made the button call the right method

naive pawn
vocal wharf
#

yeah and I've checked the "orange" method with debug.log and it is being called when I press the orange UI option

naive pawn
#

make sure you've saved all your files.

vocal wharf
#

yup they are

visual linden
#

I'd slap a breakpoint in both carColorYellow and carColorOrange to see if the wrong one is being called, or perhaps both are being called.

vocal wharf
#

the only thing I can think of is that the RBG color code I put in might be wrong

#

but it's the same color code as the color of my orange UI button

vocal wharf
naive pawn
#

50% is a pretty large difference. you'd be able to make that out if it were set correctly

visual linden
#

Learning to use breakpoints in the debugger will make your life a lot easier 😁

naive pawn
#

try logging out carMaterial.color right after you've set it, right after the Debug.Log("orange")

vocal wharf
#

hmm only the orange method is called when pressing the orange UI, and only the yellow is called when pressing yellow

#

I'm gonna try some different RBG codes in the orange method to see if those work

#

In the orange method I put the color code (255, 128, 0) for orange and when I click the orange button it debug.logs that same exact code, but the car is yellow

naive pawn
#

do any other non-0/1 colors work

#

new button, new method, new everything

#

try new Color(128, 128, 128), see if that makes it gray

#

...wait

#

Color takes floats between 0 and 1

#

not ints between 0 and 255

languid spire
#

Apart from the fact that your structure is horrible. You should be using Color32

vocal wharf
#

I just tried 255, 100, 50 and it made the car white 💀

naive pawn
#

yeah, anything above 1 is gonna be treated as 1

vocal wharf
naive pawn
#

you're thinking in ints, but Color thinks in floats

naive pawn
little meteor
#

you can also just use Color.red etc

vocal wharf
visual linden
#

I don't think it has anything to do with ints of floats,
Color is 0 to 1

vocal wharf
#

that's weird that it's 0-255 in inspector but 0-1 in code

visual linden
#

What threw me off was that supposedly the other colors worked fine ???

naive pawn
vocal wharf
#

so the code just treats it as 1, 0, 0

naive pawn
vocal wharf
#

when I do orange, I typed 255, 128, 0 and the code treats it as 1, 1, 0

naive pawn
#

they can be implicitly converted to and from each other

visual linden
#

Well yes, but surely your purple cannot have been purple

naive pawn
vocal wharf
#

I guess I'll change everything to the 0-1 system

visual linden
#

I'm glad you figured it out :D

vocal wharf
#

thanks for the help

#

I was so confused haha

tired slate
#

Hi, how to do something like, when i click a button my countCoins degresse by 5 ?

naive pawn
#

have you tried searching about that at all?

#

that's a pretty basic thing, there should be plenty of online resources about that

tired slate
naive pawn
#

ok... ask about that then

vocal wharf
naive pawn
#

if you just ask about that specific problem then you're going to get a specific answer

#

if you're stuck on how to generalize it, ask about that

#

what does "a lot of items" mean?

visual linden
# vocal wharf everything works!

If you want to simplify your code a bit, you can do something like

  ColorUtility.TryParseHtmlString(color, out Color newColor);
  material.color = newColor;
}```
Then you can set the hex value directly in the inspector for the OnClick event, 
eg "#B43B21"
#

I usually find html color codes a bit easier to work with

naive pawn
#

aw man i got so excited for a sec, until i realized it was html colors and not css colors

visual linden
#

Are they not the same thing?

#

TryParseHtmlString will take any hexadecimal color value and return the color

naive pawn
#

no, it's just referring to hex color strings and a few basic keywords here
css supports a lot more formats
rgb, hsl, hsv, and some other color spaces with function-like syntax, and keyword colors
though i guess that would be an absolute pain to fully implement since it'd have to support like css math too

vocal wharf
#

I'm just gonna stick with the code I have for right now, it does what I need it to 🙂

naive pawn
#

hardcoding everything leads to hard walls to changing those features

#

you have a lot of duplicate code there, why should it all be repeated when only one part changes? that's like, the key sign of something that should be a function

vocal wharf
naive pawn
#

sure

visual linden
#

Yup yup :)

naive pawn
#

don't forget the audiosource

visual linden
#

When you select the function in the UnityEvent in the inspector, you'll get a little input field for the string value

vocal wharf
#

👍

vocal wharf
#
public class CarColor : MonoBehaviour
{
    public Material carMaterial;
    public AudioSource audioSource;
    public void SetHexColor(string color)
    {
        ColorUtility.TryParseHtmlString(color, out Color newColor);
        carMaterial.color = newColor;
        audioSource.Play();
    }
}

visual linden
#

What do your color codes look like?

vocal wharf
visual linden
#

Remember the #

rancid badger
vocal wharf
vocal wharf
verbal dome
#

!code

eternal falconBOT
verbal dome
#

Anyway, to me it seems like you are just always attacking/starting a new attack coroutine when in range.
You probably want a cooldown timer

#

Or does canAttack take care of that 🤔

#

Is this AI code btw?

rancid badger
topaz pendant
rancid badger
long flicker
rancid badger
topaz pendant
#

Well it says that the health is 0 beforz damage

rancid badger
#

the coro i added in the playerscript for debug works exactly as it should

dense bridge
tulip nimbus
#

How can i Destroy() prefabs that are instantiated in a different Method?

When i do this:

GameObject P1Coins = Instantiate(coinprefab, ...)
Destroy(P1Coins) }```

It works, but when i do this:

```void Method1 {
GameObject P1Coins = Instantiate(coinprefab, ...) }

void Method2{
Destroy(P1Coins) }```

I know that this is because the variable is not defined in Method2, however i dont know what i can do. Creating a GameObject before all the Methods also does not seem to work
dense bridge
naive pawn
#

though keep in mind that if you call Method1 twice you won't be able to destory the first one, since the variable would get overridden. if you need to manage many objects then use a list

tulip nimbus
naive pawn
#

what do you mean by "doesn't work"

hexed terrace
#

You did it wrong then

#
private GameObject P1Coins;

private void Method1 { P1Coins = Instantiate(coinprefab, ...); }
private void Method2 { Destroy(P1Coins); }
tulip nimbus
#

So this is my entire code, excluding all of the other fields. I want it to remove a coin (The ones you get from the StartCoins Method) and from all coins that are instantiated. It really could be that i am missing something here

GameObject P1Coin;



void Start()
{
    boxot = FindFirstObjectByType<BOT_Behaviour>();

    StartCoroutine(Startcoins());
    
}

IEnumerator Startcoins() 
{
    for (int i = 0; i < 10; i++)
    {
        yield return new WaitForSeconds(0.2f);
        GameObject P1Coin = Instantiate(coinprefab, new Vector3(1.531f, 2.223f, 2.234f), Quaternion.Euler(90, 0, 0));
        AudioSource.PlayOneShot(sfx_win);
    }
    
}


public void RewardCoin()
{
    AudioSource.PlayOneShot(sfx_win);
    GameObject P1Coin = Instantiate(coinprefab, new Vector3(1.531f, 2.223f, 2.234f), Quaternion.Euler(90,0,0));
}

public void LoseCoin()
{
    AudioSource.PlayOneShot(sfx_lose);
    GameObject P1Particle = Instantiate(particle, coinprefab.transform.position, Quaternion.identity);

    if (coinprefab != null)
    {
        Destroy(P1Coin);
    }
    else
    {
        Debug.Log("No more Coins left");
    }

    Destroy(P1Particle, 1f);
}
#

could the coinprefab != null be the issue? If so i apologize

naive pawn
#

from all coins that are instantiated
you didn't read my second message then

hexed terrace
#

What is coinprefab (it's not included in the code)

rancid badger
hexed terrace
#

And what calls LoseCoin() ☝️

naive pawn
tulip nimbus
#

Ah i oversaw that, thank you!

tulip nimbus
naive pawn
tulip nimbus
#

Oh yeah i had a similar question it was about them as a whole, at that time my code was a bit simpler i appreciate it

dense bridge
rancid badger
# dense bridge Maybe you should encapsulate currenthealth with a property so that you could log...

so i found something. i recreated everything from scratch. the first time i run the code it works.
then if i stop the player and press play again, currentHealth is set to 0

public class PlayerHealth : MonoBehaviour
{
    [SerializeField] private float maxHealth = 100f;
    [SerializeField] private float currentHealth = 100f;
    [SerializeField] private Slider healthSlider;

    private void Awake()
    {
        // Initialize health
        currentHealth = maxHealth;
        Debug.Log($"Initialized Health: {currentHealth}");

        // Configure the slider
        if (healthSlider != null)
        {
            healthSlider.minValue = 0f;
            healthSlider.maxValue = 1f;
            UpdateHealthUI();
        }
    }

so maybe a problem in currentHealth = maxHealth; this line of awake? sorry but im new to unity

#

i tried to remove [SerializeField] from currenthealth but it always starts at 0

polar acorn
rancid badger
#

yeah looks like the inspector fucked me up

#

now i just have to find why slider UI is not updating lol

cosmic quail
rancid badger
#

thanks guys

heavy oasis
polar acorn
#

The inspector is designed to take precedence over the code, otherwise you wouldn't be able to set any values in the inspector at all

dense bridge
naive pawn
trim oak
#

Hi. im starting right now with Untity, but im not able to find some good websites or youtube channels. Do somebody know some?

naive pawn
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

cosmic quail
naive pawn
rancid badger
polar acorn
rancid badger
polar acorn
rancid badger
polar acorn
#

Ah, you're also changing it in TakeDamage I see

rancid badger
#

so the problem was that currenthealth is retained from the old value when i play/stop and play again

polar acorn
#

Which is called in EnemyMovement, on the PlayerHealth component of player. What is player set to on EnemyMovement?

rancid badger
#

it is the transform im using to calculate distance between enemies and player

polar acorn
#

Is player a reference to an object in the scene or a prefab

rancid badger
#

i think i dragged it from the prefabs folder

polar acorn
#

So it's a prefab

rancid badger
#

because im spawning the player with char spawner script

polar acorn
#

You're modifying the health of a prefab there

rancid badger
#

no idea how to do it properly then

polar acorn
#

For this component, instead of referencing a prefab, reference the player in the scene

mint surge
#

Hello, do you guys know why my codes aren't working with Unity ? I've set my script editor to VSC and when I make a mistake in my scripts for example type Debug.log with log lowercase then it gives an error, but if I write it correctly Debug.Log then it doesn't print the message coming after, I would really appreciate any help.

polar acorn
mint surge
polar acorn
rancid badger
mint surge
polar acorn
polar acorn
mint surge
mint surge
polar acorn
mint surge
#

All the script has to do is print in the console that is all

polar acorn
#

If you want code to run, it has to exist

#

Right now, it does not

#

Your script defines a component

#

that component is nowhere

#

so it isn't running

mint surge
#

Oh, I am still with the Roblox stuff since I am a former Roblox coder lol, in Roblox you didn't need to add them to objects for them to work

polar acorn
#

Surely they needed to exist somewhere in order to run. Code doesn't run unless something runs it

naive pawn
#

have you gone over unity essentials

mint surge
#

Let me try the stuff I got told above tho

naive pawn
#

then do that first

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

willow sand
#

my unit does not want to go into the attack state I have scripts that decide these states and an attack controller that references these scripts but now all of the sudden after i have changed nothing he doesn't want to go to the attack state I can see it through the animator tab the transitions are the same to when it worked beforehand

ionic wing
#

i coded in a room transfer, yet im being sent all the way out of bounds, not at the bush gate

#

does it have something to do with my coordinates?

naive pawn
#

well how are you spawning the player

naive pawn
mint surge
ionic wing
polar acorn
#

Or, if you need to use Unity MonoBehaviour messages like Start and Update, you'd just put them on an object

mint surge
ionic wing
#

yeah the player spawns somewhere else, idk how id find the exact coordinates

naive pawn
naive pawn
patent tapir
#

Hi im comming back to unity after learning a bit about a year ago and thought i make a flappy bird game from scratch.

I have created a game character and created a prefab with two rectangales to make the gate for the bird to fly through.

my bird can fly up and down and I am moving my pipe from right to left but getting frustrated with the collision . the bird can sit on top of the pipe but if he hits the side part of the pipe he goes straight through.
|
Any ideas

cosmic quail
patent tapir
cosmic quail
willow sand
#

i know

cosmic quail
willow sand
#

nevermind

#

sorry

#

wrong person

patent tapir
#

i created one rectangle to test this further collider covers the rectangle. same thing the bird sits on top but if i position the bird to the side the rectangle moves through the bird

#

and I get debog.log message saying character collider with rectangle

cosmic quail
flat sphinx
#

whats hte math for converting a linear function into an exponential one while keeping the limits the same

#

idk if thats the word, i mean the boundaries

patent tapir
eternal falconBOT
flat sphinx
#

currently got

var magnitude = Math.Min(Math.Sqrt(Math.Pow(dx, 2) + Math.Pow(dy, 2)), LAUNCH_DRAG_CAP) - RELEASE_THRESHOLD;

, using it for scaling an object and want to convert it so it scales along an exponential

patent tapir
# cosmic quail !code

'''cs
using UnityEngine;

public class PipeMove : MonoBehaviour
{
private Rigidbody2D rb2d;
public float speed = 2f;

void Start()
{
    rb2d = GetComponent<Rigidbody2D>();

    if (rb2d == null)
    {
        Debug.LogError("No Rigidbody2D attached to the object. Disabling script.");
        enabled = false;
        return;
    }

    // Ensure collision detection is continuous
    rb2d.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
}

void FixedUpdate()
{
    // Move the pipe using velocity for proper collision detection
    if (rb2d != null)
    {
        rb2d.linearVelocity = new Vector2(-speed, 0); // Move left
    }
}

void OnCollisionEnter2D(Collision2D collision)
{
    // Optional: Detect character collisions
    if (collision.gameObject.CompareTag("flappy"))
    {
        Debug.Log("Character hit the side of the pipe!");
        // Additional logic can go here if needed
    }
}

}

'''

#

'''cs
public class flappyFly : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{

}

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

   
if(Input.GetKey(KeyCode.Space))
{
    GetComponent<Rigidbody2D>().AddForce(Vector3.up*6);
}

if(Input.GetKeyUp(KeyCode.Space))
   {
    GetComponent<Rigidbody2D>().AddForce(Vector3.down*-2);
}
    

}

}
'''

patent tapir
#

I have to admit I did try with GTP to fix the situation so the code was adapted by the app

patent tapir
flat sphinx
# flat sphinx currently got ``` var magnitude = Math.Min(Math.Sqrt(Math.Pow(dx, 2) + Math.Pow...

code for scaling rn is

var base_x = Mathf.Sin(angle);
var base_y = Mathf.Cos(angle);

var target_x = base_x * Math.Abs(Math.Clamp(dx, -LAUNCH_DRAG_CAP, LAUNCH_DRAG_CAP));
var target_y = base_y * Math.Abs(Math.Clamp(dy, -LAUNCH_DRAG_CAP, LAUNCH_DRAG_CAP));

var arrow_scale = (float)magnitude * ARROW_SCALE_CAP;
aim_arrow.transform.position = this.transform.position + new Vector3(base_x * Mathf.Max(arrow_scale, 1), 0, base_y * Mathf.Max(arrow_scale, 1)); 
aim_arrow.transform.rotation = Quaternion.Euler(new Vector3(90, angle * (180/Mathf.PI), 0));
cosmic quail
patent tapir
barren cloak
#

Hey I am building some mini games to learn and improve, right now I am trying to build a little round based combat sample with and overworld.
When the character touches an enemy, I load the scane with the batlle UI and the fight takes place. After the fight I want to return to the previous scene in the overworld, to the spot where my character touched the enemy.
When I load into the previous scene, the whole scene got reset. Ofc I can save the position of my player and just put him there, but is there a best practice to this case? Do I really have so save everything, every position of every enemy, every switch that I flicked, etc etc when I just want to return the the previous spot?

patent tapir
#
using UnityEngine;

public class PipeMove : MonoBehaviour
{
    private Rigidbody2D rb2d;
    public float speed = 2f;

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();

        if (rb2d == null)
        {
            Debug.LogError("No Rigidbody2D attached to the object. Disabling script.");
            enabled = false;
            return;
        }

        // Ensure collision detection is continuous
        rb2d.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
    }

    void FixedUpdate()
    {
        // Move the pipe using velocity for proper collision detection
        if (rb2d != null)
        {
            rb2d.linearVelocity = new Vector2(-speed, 0); // Move left
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        // Optional: Detect character collisions
        if (collision.gameObject.CompareTag("flappy"))
        {
            Debug.Log("Character hit the side of the pipe!");
            // Additional logic can go here if needed
        }
    }
}
#
using UnityEngine;

public class flappyFly : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
       
    
       
    if(Input.GetKey(KeyCode.Space))
    {
        GetComponent<Rigidbody2D>().AddForce(Vector3.up*6);
    }

    if(Input.GetKeyUp(KeyCode.Space))
       {
        GetComponent<Rigidbody2D>().AddForce(Vector3.down*-2);
    }
        
    
    }
}
flat sphinx
#

not scaling

cosmic quail
flat sphinx
#

eh whateve ri still need a linear -> magnitude converter

cosmic quail
flat sphinx
#

can you serializefield a const

#

@cosmic quail im asking because it seems to silently fail stinker

#

and i refuse t oaccept "just dont use consts" as a solution

cosmic quail
polar acorn
flat sphinx
#

i assume there isnt an analog

#

? c

cosmic quail
flat sphinx
languid spire
#

consts are a compile time concept so serializing them for run time would make no sense

polar acorn
#

If you want to edit them, why are they consts? Stuff like those bitmasks definitely look const-like, but also probably should just be a Flags Enum

tulip herald
#

Stupid question here what's the (1<<2) stuff?

flat sphinx
languid spire
#

bit shifting

tulip herald
#

Oooh

polar acorn
flat sphinx
#

on runtime they should stay as they are

polar acorn
flat sphinx
#

no

patent tapir
# cosmic quail ok can you show the collider on the bird and pipe?
using UnityEngine;

public class flappyFly : MonoBehaviour
{
    private Rigidbody2D rb2d; // Cache the Rigidbody2D component
    private bool isPressingSpace = false; // Track if the space key is held
    private bool spaceKeyReleased = false; // Track if the space key was released

    public float upwardForce = 6f; // Force applied when space is held
    public float downwardForce = 2f; // Force applied when space is released

    void Start()
    {
        // Get and cache the Rigidbody2D component
        rb2d = GetComponent<Rigidbody2D>();

        if (rb2d == null)
        {
            Debug.LogError("No Rigidbody2D attached to the object. Disabling script.");
            enabled = false;
        }
    }

    void Update()
    {
        // Check if space is pressed
        if (Input.GetKey(KeyCode.Space))
        {
            isPressingSpace = true;
        }
        else
        {
            isPressingSpace = false;
        }

        // Check if space was released
        if (Input.GetKeyUp(KeyCode.Space))
        {
            spaceKeyReleased = true;
        }
    }

    void FixedUpdate()
    {
        // Apply upward force if space is held
        if (isPressingSpace)
        {
            rb2d.AddForce(Vector2.up * upwardForce, ForceMode2D.Force);
        }

        // Apply downward force if space was released
        if (spaceKeyReleased)
        {
            rb2d.AddForce(Vector2.down * downwardForce, ForceMode2D.Force);
            spaceKeyReleased = false; // Reset the flag
        }
    }
}

still the same, I assume this is what you meant

polar acorn
#

They still wouldn't be const, but it seems like you don't actually want consts anyway

tulip herald
#

Ooh that's what layermask are pretty cool, you learn something new everyday

flat sphinx
#

thats sad

polar acorn
#

If you want to change the values, you shouldn't use constants, which are defined by their inability to be changed

cosmic quail
flat sphinx
#

and keep them as is on runtime

naive pawn
flat sphinx
#

which i CAN do by tweaking the code

polar acorn
flat sphinx
#

and im complaining that i cnat do that in the editor

naive pawn
polar acorn
#

But you want to serialize them to a file and deserialize them. That's not a thing consts do

#

Why do you need them to be consts?

flat sphinx
#

because im not planning to change them on runtime???

naive pawn
#

that's not what const means

flat sphinx
#

so slap a const on top???

polar acorn
#

Okay, but why do they need to be const

naive pawn
#

a const field means it doesn't change ever

cosmic quail
polar acorn
#

Are you trying to use them in a field initializer?

#

Are you trying to put them in some other compile-time use case?

flat sphinx
naive pawn
#

@flat sphinx by "change at runtime" do you actually mean like, runtime in code, or in play mode in the editor

patent tapir
cosmic quail
twin bolt
#

Question, I have a development-only prototyping room, that is getting 200 FPS because their is pretty much nothing in it, my issue is that the players input is delayed at that 200FPS, but is fine at 60FPS. Why is that?

naive pawn
naive pawn
twin bolt
naive pawn
polar acorn
#

Input should not be done in FixedUpdate

twin bolt
vocal wharf
polar acorn
#

Read input in Update, move rigidbodies in FixedUpdate

patent tapir
naive pawn
#

@flat sphinx when you say you don't want to change it at runtime, do you mean that you want to make it grayed out in the inspector while in playmode in the editor, or disable modifying through other code that is executed while in playmode/build

vocal wharf
patent tapir
flat sphinx
#

or whateve the not-play mode is called

tulip herald
#

Editor mode

naive pawn
tulip herald
#

Yeah const means it will never change in editor or runtime?

vocal wharf
naive pawn
#

const is about how the code acts internally to itself, unrelated to the unity editor

cosmic quail
polar acorn
#

const means it is a compile time constant. Code only compiles when a script file changes. Changing the values of assets does not cause code to recompile. Changing a value in the editor is antithetical to what const means

flat sphinx
patent tapir
cosmic quail
flat sphinx
#

god forbid we let unity change a script file

tulip herald
#

It's not a huge deal fortunately

naive pawn
cosmic quail
naive pawn
#

that would be a massive pain actually

flat sphinx
patent tapir
polar acorn
flat sphinx
#

and most editors have hot refresh anyways

naive pawn
#

and yknow, it'd break any formatting that the fields had to begin with, since formatting isn't kept when stuff is compiled

polar acorn
#

Seems to me like you just got told "use const as much as possible or your code is bad" and never actually bothered to learn what const does

naive pawn
#

except for debugging i guess

#

marking something that does change as const just doesn't make sense lol

naive pawn
#

idk why you're making this a big deal, const is not that important

#

this isn't js where const is necessary

vocal wharf
polar acorn
#

It literally just gives you access to the variables in compile-time use cases like field initializers and parameter defaults

#

It doesn't even give any noticeable performance increase

#

Because floats are value types already

patent tapir
flat sphinx
#

also just ocd

polar acorn
#

Well, no noticeable performance increase over static variables at least. If they're non-static you could have redundant copies

naive pawn
polar acorn
#

But a ScriptableObject or static class would serve the same purpose

flat sphinx
polar acorn
#

It's an object oriented language, that's kind of what it's designed to do

naive pawn
#

if it helps, think about this;
c# usually has 2 steps, compiletime and runtime
but unity adds another step in between, where it injects values set by the editor
const doesn't really fit into the picture that unity sets
const is for "constant", and stuff that's set by the editor can't be constant, otherwise the editor wouldn't be able to set them

flat sphinx
cosmic quail
polar acorn
flat sphinx
polar acorn
#

But we're talking literal bytes of memory in an era where you can get 16GB of RAM for the price of a chicken sandwich

flat sphinx
#

also yeah that

#

savings that are literally not worth thinking about

naive pawn
flat sphinx
#

this is JUST ocd

naive pawn
patent tapir
naive pawn
cosmic quail
flat sphinx
naive pawn
#

it's a modifier, is it not just a compiletime thing thonk

flat sphinx
#

granted its more of a nudge on stuff it probably already knows

naive pawn
#

but also; stuff you never assign to can be "effective consts", and the compiler can optimize them just like actual consts
that's a thing in java, and i think c (gcc), not sure if that's a thing in c#

#

it probably is

flat sphinx
#

i think consts you could optimize down into.. well, consts, in assembly

#

but this is cshart so thats not it either

cosmic quail
flat sphinx
#

dont remember jack shit from it lmao

twin bolt
#

How can i enable/disable a render feature from a script during runtime?

naive pawn
slender nymph
slender nymph
naive pawn
#

ah whoops

#

coming from java where they aren't separate things, mb

patent tapir
frail hawk
#

imagine every flappy bird game was published somewhere 😉

cosmic quail
#

im confused as hell man does anyone else know whats going on here?

the bird can stand on a pipe but when going through the side it goes through???

patent tapir
short hazel
#

The pipes themselves could be moved in a way that does not respect physics

#

Like by altering transform.position

cosmic quail
#

and they were both in fixedupdate

short hazel
#

Then the colliders are not setup so they interact correctly. Both need to be non-trigger ones

patent tapir
naive pawn
#

probably not something this simple

short hazel
#

But since you lose when you touch a pipe, you can get off with having the pipes as triggers, and check in OnTriggerEnter2D on your player

patent tapir
patent tapir
cosmic quail
patent tapir
naive pawn
#

(what was the glitch)

patent tapir
#

I am using Universal 2D core template to begin the project

patent tapir
naive pawn
#

...and the rectangle is a rigidbody + collider?

#

isn't that what's supposed to happen

#

oh wait

#

middle as in, through the pipe?

cosmic quail
#

yeah

patent tapir
#

yes

naive pawn
#

ive been thinking you meant between the pipes lmao
i was so confused

#

are the pipes a single rigidbody or 2 separate rbs

patent tapir
#

the top and bottom have there own collider and rigid body

twin bolt
#

How can i enable/disable a render feature from a script during runtime?

naive pawn
patent tapir
#

been driving me crazy

cosmic quail
naive pawn
#

are they boxcolliders or platform colliders

patent tapir
#

box collider 2d

naive pawn
#

and they're extended along the size of the pipe?

cosmic quail
#

could it be cause the pipes are scaled? also why is the bird's scale 0.2

naive pawn
#

wait isn't it just because that's how kinematic rbs work

#

kinematics aren't simulated, they just move and dynamics can collide with kinematics

cosmic quail
naive pawn
#

If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore.

#

the collision doesn't stop the pipes from moving left

#

and the bird is constrained on the X axis

#

so they're just forcibly phasing through each other

quartz anvil
#

Having trouble setting Materials to an array? my array size is getting set but the materials are not(in the editor)```cs
public class ShipCore : MonoBehaviour
{
public Material[] MaterialArray = new Material[3];
public Material Material;
public Material TransMat;
public Material ThrustEmission;

public void Start()
{
MaterialArray[0] = Material;
MaterialArray[1] = TransMat;
MaterialArray[2] = ThrustEmission;
}

}
}

naive pawn
#

have you tried just adding OnCollisionEnter2d messages to debug

naive pawn
smoky gale
#

does the bird have a fixed x position by any chance

patent tapir
naive pawn
cosmic quail
naive pawn
#

they're just phasing through each other

smoky gale
patent tapir
#

omg

cosmic quail
#

🎉

patent tapir
#

he was spinning so tried to stop it

naive pawn
#

you only need the freeze rotation for that

cosmic quail
patent tapir
#

wow thank you

naive pawn
smoky gale
#

y would prevent jump

#

x axis fixing would be fine as long as the game stops as soon as the collision happens and the bird falls in place

cosmic quail
#

oh, i see

smoky gale
#

i'm guessing you're following the GMTK tutorial

patent tapir
#

no i am trying to figure it out my self

#

i did a bit of unity a year ago

#

but i did turned to chat gpt who made my code fancier with error debugs built in ect

naive pawn
#

yeah maybe don't do that

patent tapir
#

was desprate, going to start again this time just freeze z lol

#

next job create a spawn manager 🙂

barren cloak
#

Hey. is there a quick way to go back to a scene in its previous state?

slender nymph
#

use the version control software that you are surely using since it is the sane thing to do in order to revert to a previous commit for that scene

barren cloak
#

no no i mean in game, so i leave the scene because a battle menu pops up (another scene) and then want to change back to the other scene

#

And when i use loadscene with the buildindex, the scene is completly reverted to it's start state

slender nymph
#

you need to set up some way to store the state of the objects in the scene. because just loading the scene again is expected to do what you are experiencing

barren cloak
#

Ah damn, I thought there would maybe be a quick way and I would not have to do this..^^ Thank you

magic panther
#

How do you guys go about saving game progress to a save file (new file, all that) ? Like the current xp, inventory, would xml be good for it?

slender nymph
#

xml is fine, yes. or unity already has jsonutility built in to serialize to json. or there are plenty of third party options for serialization like json.net or message pack (which encodes to binary)

magic panther
#

I'll look into them, thanks for mentioning

flat sphinx
#

help my logic isnt logicking

#

shoot_blockers is reset immediately to 0 after shooting and that should only be possible through the update block

polar acorn
#

Try logging it after you change shoot_blockers in OnMouseUp. See if it's 0 after those changes, or if it's changing somewhere else

#

Since you just need to check if it's zero or not, you don't need to worry about printing it as binary to see which flags are on, but that could come in handy too

short hazel
#

It's been a while since I've seen that much bitwise ops, looks like I'm back with C
Surely there's a more readable way of doing this

flat sphinx
flat sphinx
#

ama throw a spare Debug.log tho just in case c# broke bits

short hazel
#

The bitops are not, it hinders readability
We have enums here which can help

polar acorn
#

But that's a bold assumption to make

short hazel
#

Or even bool variables lol

steep rose
#

some messages will be blocked by the discord, for good reason

polar acorn
#

If, for example, AIM_LOCK_MOVEMENT is 0, then the result could very well be 0

polar acorn
#

Okay, so it's not zero after OnMouseUp. Where are you seeing it at 0

flat sphinx
#

if i drag and hold its 1
when i release it it turns to 0

#

only the update function unsets that flag

flat sphinx
polar acorn
flat sphinx
polar acorn
#

You would never actually be able to see the value between an OnMouseUp and Update

#

So, if it's getting set to 0 in update, you're going to see it at 0

flat sphinx
#

did you.. even read the code

#

im trying to check if the ball hasnt moved in the past .25 seconds
if it hasnt, unset the movement flag

polar acorn
#

Yes, and I see a place where you remove AIM_LOCK_MOVEMENT from it, which would remove the only thing that it's currently set to

flat sphinx
#

clearly the issue is either how i compare the times, or how i measure them

flat sphinx
#

oh okay i figured it out i just didnt reset the value on launch

#

also checked against hte wrong value being 0

#

yeah it works now

#

yay me

barren cloak
#

I spawn enemies (gameobjects) in my scene.
I want to save this scene in it's current state. So I created a list of gameobjects and put every enemy gameobject into that list, after scene change all gameobjects are empty. okay i get that.
Next approach was saving just the position data of the enemies and the prefabtype, so I can just iterate through this list, when the scene is loaded the next time and Instantiate all objects with the prefab and the position data. But I am not able to get the prefab data in runtime, is my approach totally wrong?

raw light
#

can anyone assist me im trying to setup my project and when trying to create a player prefab of my character with this script attached it wont let me

slender nymph
#

you need to be more specific than "wont let me"

raw light
#

my bad let me post the error

#

The error says You are trying to save a prefab that contains the script. which does not derive from monobehaviour

slender nymph
raw light
#

Please change the script to derive from monobehaviour or remove it from the game object playercontroller

polar acorn
#

If it's attached to an object it needs to be a MonoBehaviour

raw light
#

it wont let me attache the script now to the player prefab

#

heres my script

polar acorn
#

If it's attached to an object it needs to be a MonoBehaviour

slender nymph
raw light
#

yea i did i appreciate it

slender nymph
#

so you've confirmed you have 0 errors, the component inherits from monobehaviour, etc?

raw light
#

heres my code i think i did it correctly

#
using Unity.Netcode;
using UnityEngine;
public class PlayerControllers : MonoBehaviour
{
#

couldnt post the whole code

polar acorn
slender nymph
eternal falconBOT
raw light
#

theres my code sorry it took so long

slender nymph
#

well those are different classes

polar acorn
raw light
#

i replaced network behaviour with MonoBehaviour and it didnt work

slender nymph
#

well yes, you would have had many compile errors doing that (well, maybe just a couple)

polar acorn
#

Show a screenshot of your Console

raw light
#

ok one moment

#

apparently theres quite a few errors

#

in my console log in unity

#

let me start a new fresh blank project

slender nymph
#

or you could just, idk, fix your errors?

#

that's literally the reason you are experiencing this

#

and was step 2 in the link you said you followed the instructions from

polar acorn
#

That wasn't a rhetorical question, you can't add any components while you have compile errors

raw light
#

i got it to work! thankyou guys ur a blessing

rocky canyon
#

are you using the new input system or legacy?
if the new have u used the input debugger to see if it is indeed not working at all.. or not working in the way u expect.. (just brainstorming)

#

i have an RC Radio i use for fun.. and it'll display on that website a certain way but in unity the mapping is a bit different.. (still works.. but not where i expected to see it)

fickle summit
#

can someone help me with one of my methods that doesnt work (im new to unity and its coding language)

slender nymph
#

!ask

eternal falconBOT
fickle summit
#

ive tried many differnet things to see if it would work but it still doesnt

steep rose
#

show us your code and what isn't working as well as any errors you are getting, if any.

#

!code

eternal falconBOT
fickle summit
#

heres the full code, no errors in it showing in the log

#

the method that isnt working is the HandleSlide

slender nymph
#

you still haven't even said what the actual problem is

fickle summit
#

im sorry im un familar how im suppose to ask in this server

slender nymph
fickle summit
#

the problem is that when the slide method is used it suppose to move the player forward, but it doesnt work and i dont know why. changing to vector2.up or down works but left or right doesnt

slender nymph
#

what do you mean "it doesn't work" what does not work? do you mean it does not move the player in the expected direction? does it not move the player at all? you have to provide actual details

hardy maple
fickle summit
#

it doesnt move the player at all

hardy maple
#

oh nvm I see it

slender nymph
# fickle summit it doesnt move the player at all

i'm gonna go ahead and assume you are modifying the velocity of the rigidbody in a different component every frame which would, naturally, overwrite the velocity you've set at the beginning of that coroutine

fickle summit
#

so how do you think i should solve this?

slender nymph
#

you need to not overwrite the velocity for the duration of the slide. this component has a reference to the PlayerMovement component, which is where i assume you set the velocity each frame, so tell it when it can and cannot set the velocity

fickle summit
#

okay i will try to do this and see if it works

#

thanks for the help and suggestions!

modest linden
#

Can someone help me with this script? I'm trying to make the code spawn a prefab every 1.5 seconds then after 0.2 seconds it spawns it again using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PeaSpawner : MonoBehaviour
{
public GameObject Pea;
public float Cooldown;
public float Cooldownset;
public float Timetorespawn;
public float Timetorespawntwo;
public bool Shooting;
public bool Reapeat;
public BoxCollider2D BC2d;
// Start is called before the first frame update
void Start()
{
Cooldown = Cooldownset;
}
// Update is called once per frame
void Update()
{
if (Shooting)
{
if (Timetorespawn < 0)
{
Timetorespawn = Cooldown - 0f;
UnityEngine.Object.Instantiate(this.Pea, this.transform.position, this.transform.rotation);
if (Reapeat)
{

            }
        }
        if (this.Cooldown > 0f)
        {
            this.Timetorespawn -= 1f * Time.deltaTime;
        }
        if(this.Cooldown > 0f)
        {
            if (Reapeat)
            {
                this.Timetorespawntwo -= 1f * Time.deltaTime;
            }
        }
        if (Timetorespawntwo > 0f)
        {
            if (Reapeat)
            {
                Timetorespawntwo = Cooldown - 0f;
                UnityEngine.Object.Instantiate(this.Pea, this.transform.position, this.transform.rotation);
            }
        }
    }
}

}

swift crag
eternal falconBOT
swift crag
#

(gdl.space is broken right now, so use another site)

swift crag
#

What is the problem?

#

You've described what you want it to do, but not what the issue is

forest summit
#

am i allowed to post a video here?

swift crag
#

yes, to show your problem

forest summit
#

alright

swift crag
#

this checks if the amount of time left is greater than zero

#

which would spawn a projectile every single frame

modest linden
#

i realized that

#

i wiil meake it <

forest summit
swift crag
#

assuming that you have them different values, at least -- right now they're both set to Cooldown

rocky canyon
swift crag
#

1E-08 is 10^-8

#

which is one millionth

#

It's probably some other very very tiny number even when 0 is displayed

forest summit
#

i see

#

but they are alternating between positive and negative values right?

modest linden
#

I fixed it 🙂

swift crag
#

Sure, but they're very very tiny

rocky canyon
#

well.. miniscule amounts above and below zero

#

but yes

#

it does its best damnit..

#

(╯°□°)╯︵ ┻━┻

forest summit
#

cause what my plan was for my jump script was to just check if the y velocity was 0 and if it was you could jump otherwise you wouldnt be able to

#

which is probably the least effective way about doing it

swift crag
#

that would let you jump forever if you jumped at the apex of your previous jump

rocky canyon
#

pro-gamer moves ^

forest summit
#

true i didnt think of that

steep rose
#

you would want to check if you are grounded as well

swift crag
#

the most common way I've seen is to test if there's ground beneath your character

steep rose
#

if you do that method

forest summit
#

i have tried this OnCollisionEnter method but it didnt seem to work for me

swift crag
#

you could use a query method, like Physics2D.OverlapBox

swift crag
steep rose
#

you could also do a ray/spherecast

forest summit
#

or on collision stay it was

steep rose
#

if needed

rocky canyon
#

i love my raycasts ➡️

swift crag
forest summit
#

ohhhhh

rocky canyon
#

my current 2d character seems to use CapsuleCasts tho

swift crag
#

and it could still be fiddly

forest summit
#

i bet that was the issue

swift crag
#

Physics messages are very commonly messed up

#

I used to struggle to make them work right

#

this explains how to use them very nicely

steep rose
#

which is only called once

forest summit
#

i was using oncollisionstay

#

i just mixed them up

copper crest
#
using UnityEngine;

public class GameRush : MonoBehaviour
{
    public void GoldRush ()
    {
        FindObjectOfType<GameManager>().GameEnd();
    }
}
#

it just dosent work, it spams the ui

polar acorn
copper crest
eternal falconBOT
copper crest
#

aight

#
using UnityEngine;

public class GameRush : MonoBehaviour
{
    public void GoldRush ()
    {
        FindObjectOfType<GameManager>().GameEnd();
    }
}```

```cs
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    bool gameHasEnded = false;
    float WaitRestart = 0.5f;

    public GameObject completeUI;
    public GameObject goldRushUI;

    public void CompleteLevel()
    {
        
        if (SceneManager.GetActiveScene().buildIndex == 7)
        {
            goldRushUI.SetActive(true);
        }
         else
        completeUI.SetActive(true);
    }

    public void GameEnd()
    {
        if (gameHasEnded)
        {
            gameHasEnded = true;
            Debug.Log("GAME OVER!!!!!");
            Invoke("Restart", WaitRestart);
        }
    }

    void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
polar acorn
copper crest
#

yes it also works in other scenes when OnCollisionEnter calls GameEnd()

polar acorn
#

Is this object destroyed or deactivated before WaitRestart amount of time has passed? Try putting a log in Restart and see if it's called

copper crest
#

nah isnt called.

copper crest
#

instead of calling game end and progressing to Restart()

#

i just called the SceneManager function in the animation event script

#

works just fine!

#

thanks for your help @polar acorn !

#

<3

#

OH SHIT

#

IT JUST COMPLETELY BROKE THE GAME MANAGER SCRIPT LOL

rocky canyon
#

glad i could help

grave lichen
#

that close to what i want but i more want it to move with the mouse no matter what no really scroll to the right if the mouse is 50 to the right or whatever

rocky canyon
#

just use a first-person type camera.. ignore the "Vertical" (Y) axis and clamp the horizontal (X)..

#

use a really slow movement multiplier

#

but the video does seem more like its just a slow scroll animation or something

grave lichen
#

i can only send a 10MB video here

rocky canyon
#

oh thats just a simple mouse parallax

grave lichen
#

like i hope show enough

#

cause how im gonna learn unity is not by watch learn unity im gonna learn by making a fnaf game

rocky canyon
#

its mouse movement <- -> translated to rotational movement..

#

^ yea, its probably pretty simple with cinemachine

#

has clamps and stuff built in

grave lichen
#

it not really like this cause like you can see one half of the office and then when you move to the right you can see more of the right side and less of the left side

rocky canyon
#

ya.. when u turn ur head to the right.. u see less of the left of ur bedroom correct?

grave lichen
#

yeah

#

it like that

rocky canyon
#

yea, its camera rotation..

#

thats all it is.. paired w/ mouse movement left and right

grave lichen
#

it cant be WASD

#

it need to be mouse

rocky canyon
#

the desk is a 3D space..

#

not a picture

grave lichen
rocky canyon
#

its a pre-rendered 3d scene...

grave lichen
#

yes

#

but they are PNG

#

in the game

rocky canyon
#

have u looked into how to do those?

#

im absolutely clueless on how to deal w/ images and videos like that

#

maybe put it on a curved mesh? lol

grave lichen
#

well the game i show was made in clickteam

#

it wasnt made in unity

rocky canyon
#

so ur gonna jump str8 into making a fnaf clone?

grave lichen
#

yea

#

that how i learn clickteam

grave lichen
#

and that how i somewhat learn GM

rocky canyon
#

you're gonna just have to start googling around

#

not a very common thing to do i'd imagine

grave lichen
#

to have a camera move with the mouse?

rocky canyon
#

no, that parts easy

grave lichen
#

cause that how you do it

#

that all i need

rocky canyon
#

well i told u ages ago how to find that

#

and as did vengeful

tiny hawk
#

Hey guys, this might sound like a very beginner coding question.

I downloaded a project from Github. And it's giving this error saying this class or namespace doesn't work.

Are .Classes treated in a special way when doing imports?

Perhaps it has to do with where I placed the files I imported?

rocky canyon
#

its just a free-look camera w/ the vertical part ignored.. 🎦

grave lichen
#

yeah

rocky canyon
#

u can program ur own.. or u can use cinemachine..
just research via google.. pick which method u want and you'll find bazillions of tutorials and resources..

#

if u get stuck come back

grave lichen
#

i guess you can just make a fake mouse object and make that follow the mouse? and then make that object a child of the 2D camera

#

thats how i did it in gamemaker

#

it was just more like what you said at first

modest linden
#

!code

eternal falconBOT
modest linden
umbral bough
#

Hi, before I start, please @ me when replying because I am likely to fall a sleep before seeing your answer, thanks.
I am trying to create a data type that can be serialized in json.
It's working well so far, with one exception.
If I don't inherit from anything, it can't be null.
If I inherit from UnityEngine.Object, json utility never fills it with data(ig it's incompatible?).
If I use ScriptableObject it requires me to create an actual instance of that so, no thanks.
Is there an alternative I am missing?
I explicitly need the object to be null by default and also be able to get a value from the json utility.
Thanks in advance!

modest linden
#

I am tring to make Timers(floats )in sync

rocky canyon
modest linden
#

i will show video

grave lichen
rocky canyon
#

what is a "camera 2d"? .. it can go anywhere (any gameobject).. the script doesn't matter where it is as long as the "Camera" set to Orthographic mode was assigned.. in the script

#

this is kinda why learning the basics first instead of jumping str8 in makes a difference.. knowing this stuff will just fast-track ur development

#

the "fun" stuff yakno.

grave lichen
#

camera 2d is what godot calls the camera and if it a 3D game then its camrea3D

rocky canyon
#

oh, well ur in a Unity discord now.

modest linden
#

its taking a long time, so im trying to make a instanced object Practically make another instanced object a certain times in a row and it is not being in sync

rocky canyon
#

use a coroutine

modest linden
rocky canyon
#

depends on what ur trying to do.. i also am a bit confused on what kinda syncd ur talkin about.. whats not syncing up with what?

modest linden
rocky canyon
#

what pattern?

#

im soo lost.. lets see some code.. maybe that will clear it up

modest linden
#

1.5,1.7,1.9,2.1 seconds

rocky canyon
#

ya, u should use a coroutine for that type of stuff

#

WaitforSeconds

modest linden
# rocky canyon `WaitforSeconds`

code:if (Shooting)
{
if (ShootingTimers[0] < 0f)
{
ShootingTimers[0] = ShootingTimersSet[0];
this.shoot();
}
if(Shooting)
{
ShootingTimers[0] -= 1f * Time.deltaTime;
}
if (Reapeater)
{
if (ShootingTimers[1] < 0f)
{
ShootingTimers[1] = ShootingTimersSet[1];
this.shoot();
}
if (Shooting)
{
ShootingTimers[1] -= 1f * Time.deltaTime;
}
}
if (Gatling)
{
if (ShootingTimers[1] < 0f)
{
ShootingTimers[1] = ShootingTimersSet[1];
this.shoot();
}
if (Shooting)
{
ShootingTimers[1] -= 1f * Time.deltaTime;
}
if (ShootingTimers[2] < 0f)
{
ShootingTimers[2] = ShootingTimersSet[2];
this.shoot();
}
if (Shooting)
{
ShootingTimers[2] -= 1f * Time.deltaTime;
}
if (ShootingTimers[3] < 0f)
{
ShootingTimers[3] = ShootingTimersSet[3];
this.shoot();
}
if (Shooting)
{
ShootingTimers[3] -= 1f * Time.deltaTime;
}
}
}

grave lichen
#

so i can learn unity

rocky canyon
#

lol.. ur code makes me chuckle

grave lichen
#

me?

rocky canyon
#

ive not seen anything like that in a while.

grave lichen
#

oh i didnt see the long messages

rocky canyon
grave lichen
rocky canyon
eternal falconBOT
modest linden
rocky canyon
#

helps make it readible for everyone *including those on mobile)

rocky canyon
rocky canyon
modest linden
#

the same thing happen

rocky canyon
#

its just cleaner.. than what u had..

#

i still think u should try to use coroutines for something like this..

modest linden
rocky canyon
#

im trying to think how u could do this w/ coroutines..

#

what all fire-rates do u have?

#

and do u have like single-fire, repeater (im assuming semi-automatic, and then full-auto, Gatling)?

modest linden
#

4 shots is gatling

rocky canyon
#

nah, u could do the same in deltaTime.. coroutines are nice and readible and easier to work w/ if theres other delays u need to deal w/ eventually

#

all opinion tho..

grand rose
#

does OVRInput work anymore or is it deprecated?

rocky canyon
#

i do a tickmanager w/ coroutines so im biased i guess..

slender nymph
#

WaitForSeconds is still dependent on frame time because it's processed at specific parts of the frame. deltaTime counters also experience this. I like to do this to sort of solve that:

public void Update() //can optionally be a coroutine with a while loop, either works
{
  timer += Time.deltaTime;
  while(timer >= timerThreshold)
  {
    timer -= timerThreshold;
    TimerAction?.Invoke();
  }
}
rocky canyon
#

aye ya, i didnt even think about that for some reason lol

#

mine are UnityEvents

#

my AI brains AddListener for it

slender nymph
#

just a generic standin for any event or action

slender nymph
cosmic dagger
#

using WaitForSeconds is limited as you can't check anything within the time you wait. using deltaTime allows you to do that . . .

slender nymph
#

it's not MonoBehaviour.Invoke, it's how you raise an event or invoke a delegate

#

it's for events and delegates which are just in c#, not unity specific

#

there is also UnityEvent which is similar and has its own Invoke method too, though it's not technically an event

cosmic dagger
#

you'll use that a lot. it's very handy . . .

slender nymph
#

also those are events

#

there's no "optimal" way to use the input system, there are also like half a dozen ways to use it, just use whichever is most comfortable to you and fits your needs best

cosmic dagger
#

i wouldn't say there is an optimal way; it depends how you build your project. most use UnityEvents and setup everything in the editor or C# events and do their setup in code/scripts . . .

sour snow
#

how would i begin scripting?

cosmic dagger
#

some people still poll the input in Update even though they can just receive the input as an event. . .

cosmic dagger
eternal falconBOT
#

:teacher: Unity Learn ↗

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

sour snow
#

i just feel like unity learn isnt helping

cosmic dagger
cosmic dagger
# sour snow ok thanks

make sure you put everything into practice. when you learn or follow something, repeat what you just learned without looking at the material to see how much you remember. while learning or watching a video, make sure you understand every line of code you write before moving onto the next one . . .

swift crag
#

I know the way I use it!

#

it must be the optimal one 😉

#

I like to use InputActionReference to directly refer to specific input actions wherever I need to receive input

sour snow
#

Alright but what is IMO?

#

oh 😭

swift crag
#

I do use those callbacks.

#

e.g.

#
public override void Enter()
{
    base.Enter();

    interactActionReference.action.performed += Interact;
    commandActionReference.action.performed += Command;
    // more stuff
}
#

I have an InputManager singleton that turns action maps on and off based on the current game state

#

e.g. it turns on humanoid-specific actions if you're controlling a humanoid character

rocky canyon
#

u could have it track the player via code so rotation isnt a factor

#

because it rotates with the Player too

#

have u checked the asset store or looked to see how unity's third person character does it

#

may be something enlightening

swift crag
#

one of my camera modes is an orbiting camera that doesn't rotate with the player

#

it just defines the radius you get at various elevations

#

I often make it narrow at the bottom and top, and make it wider in the middle

#

anyway, yeah, I use a Cinemachine Third Person follow component

rocky canyon
#

use a sphere and stick a camera to it (mimic the players up direction for the camera so it doesnt spin)

#

😛

swift crag
#

and a Cinemachine Same As Follow Target for the rotation control (I need to replace that)

It follows an object on the player that's being rotated by a script to have a consistent rotation, even as the player rotates

#

basically just

#
public override void Look(Quaternion rotation)
{
    Look(entity.transform.position + Vector3.up * 1.5f + rotation * (10 * Vector3.forward));
    desiredLookRotation = rotation;
    thirdPersonRoot.transform.rotation = rotation;
}

the other Look method does some more work that's not important here

rocky canyon
#

no clue, i typically only work w/ first person and top down (3/4) views

#

i thought the 3 orbit thing was just how its done

swift crag
#

(i am popping out for the night, btw)

copper crest
#

who wanna play test my game??

queen adder
#

Can someone explain to my how to access the Array in the Physics.OverlapBox Funtion? What i tried

#
    private bool isOnPlant() {
        if (Physics2D.OverlapBox(new Vector 3(Position),new Vector2(WaterSize),0,WaterLayer,)) {
            currentPlant = results[0].gameObject.GetComponent<PlantLogic>(); //// This One 
            Debug.Log("Is On Plant");
            return true;
        }
        return false;
    }
visual linden
queen adder
frail hawk
#

hmm then why are you using Physics2D in your code.

dense bridge
tranquil vault
#

I have a small problem, I'm trying to make a script that allows me to switch scenes with buttons. The thing is I have three screens I want to change to, this is for a UI assignment.
This is my current code:

#
{
    public void SwitchScene()
    {
        SceneManager.GetActiveScene()=op;

        if (op == 0)
        {
            SceneManager.LoadScene(1);
        }
        else if (op == 1)
        {
            SceneManager.LoadScene(2);
        }
        else
        {
            SceneManager.LoadScene(0);
        }

    }


}```
#

I'm 100% sure this is wrong, but I've been at it already for a good 30 minutes now

vast stirrup
#

why does the same line of code not work in different scripts?

frail hawk
#

what does the error message say

burnt vapor
#

I would put my money on that you forgot to include the namespace.

tranquil vault
#

Do I try to get the active scene, convert that to an integer and then try to put it back in?

burnt vapor
burnt vapor
#

Is this just a general "is this okay?" question, or..?

#

You mention it's wrong

tranquil vault
#

Not really, since I know the code is wrong

#

Yeah

burnt vapor
#

But why is it wrong? Is there an error? Does it not work?

tranquil vault
#

Yeah, an error shows up

#

I'll post it

burnt vapor
#

If you want to be helped you should post all the context, not just parts

tranquil vault
#

Assets\Scripts\SceneManager.cs(17,18): error CS0103: The name 'op' does not exist in the current context

#

That is the entire script

burnt vapor
#

Well, seems clear enough?

#

You try to assign the current value of op to SceneManager.GetActiveScene()

#

There are multiple things wrong here

#

I suggest you take a good look at the code. I would prefer you learn this yourself rather than spoonfeeding the answer

tranquil vault
#

Yeah, I thought that as well, I wanted to get the value of the current scene, and then have some sort of increment that changes the scene, but I didn't know how to achieve that

visual linden
burnt vapor
#

And there we go. Somebody proceeds to completely spoonfeed the answer rather than help you learn how to write better code

frail hawk
burnt vapor
#

For beginners, the variable is not defined

#

You have also switched the order. You should assign op and not SceneManager.GetActiveScene()

tranquil vault
#

Alrighty then

burnt vapor
vast stirrup
#

so now it looks like transform.position = UnityEngine.Vector3.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);

frail hawk
#

yep, i was pretty sure you had the other namespace imported as well

#

in generel you won´t need it, get rid of the System.Numerics

vast stirrup
#

i am just confused why it would perfectly work in the other script but not in this one

burnt vapor
#

Unity has its own numerics system. System.Numerics is .NET's build in numerics

#

The issue is they both have Vector3 structs

#

Alternatively if you do end up having two classes with the same name, you can for example also put this on the top of the file:

using Vector3 = System.Numerics.Vector3;
#

A good example is the Random class. It exists in both UnityEngine and System

tranquil vault
vast stirrup
burnt vapor
frail hawk
#

just read what FusedQ said.

burnt vapor
#

Ambiguity errors are common so it's worth to mention you have multiple fixes here

#

Your solution of specifying the full path is the ugliest one imo

tranquil vault
#
    {
        int op;

        op = SceneManager.GetActiveScene().buildindex;

        if (op == 0)
        {
            SceneManager.LoadScene(1);
        }
        else if (op == 1)
        {
            SceneManager.LoadScene(2);
        }
        else
        {
            SceneManager.LoadScene(0);
        }

    }```
This is how it looks now, but I get a new error
#

Assets\Scripts\SceneManager.cs(13,44): error CS1061: 'Scene' does not contain a definition for 'buildindex' and no accessible extension method 'buildindex' accepting a first argument of type 'Scene' could be found (are you missing a using directive or an assembly reference?)

#

How would I define the build index?

burnt vapor
frail hawk
#

if you have the same Class within 2 namespaces, then you have to define which one you want to use. in your case you have 2 namespaces the one form unity and the one from System.Numerics. Because both of them have Vector3 inside. If you compare both scripts one of them should have System.Numerics the other not.

tranquil vault
#

Actually yeah, let me try strings instead

burnt vapor
tranquil vault
#

wait no, that won't work

astral falcon
#

Let me revert my statement 😄 I was reading too fast, my bad.

astral falcon
#

which leads to the assumption, that you should check your !ide

eternal falconBOT
burnt vapor
#

My thought exactly

tranquil vault
#

omg I did

burnt vapor
#

I get the feeling your editor is not configured. It would help you with these things

tranquil vault
#

it works now

#

I just mispelled buildIndex

astral falcon
#

yeh, but your code editor would have told you

burnt vapor
#

Does the editor help you with auto completion of the member? Please note you should really configure it

#

These things are trivial in that case

tranquil vault
#

I guess I haven't had it configured

burnt vapor
#

Go ahead and do that. It will help you greatly. Check the bot link below Twentacle's message

tranquil vault
#

It does sometimes, with some things it auto completes, and other phrases not really

burnt vapor
#

It probably works for .NET features in general. It doesn't know about Unity features yet

tranquil vault
#

Alrighty then, I'll check it out and configure it when I have the time

#

But anyways thanks for the help

astral falcon
#

The time you save doing it asap will be compensated 😉 😄

willow sand
#

my unit does not want to go into the attack state I have scripts that decide these states and an attack controller that references these scripts but now all of the sudden after i have changed nothing he doesn't want to go to the attack state I can see it through the animator tab the transitions are the same to when it worked beforehand

burnt vapor
eternal falconBOT
burnt vapor
#

I suggest you check if your methods are called, first of all

willow sand
#

can you join our call because theres a lot of scripts and states and coliders

burnt vapor
#

Nope

#

If you can't figure out the related code then I suggest you start with checking if the methods are called

#

Check for actual proof, for example by placing a Debug.Log at the start of methods and at different steps.

willow sand
#

the methods are called the debugs say so

burnt vapor
#

Alternatively there are other ways to debug

burnt vapor
#

Does it go all the way to the invoke to set the attack state?

willow sand
#

it doesn't move into the attack state

burnt vapor
#

So what's the code that sets the attack state?

#

Surely you can share that

willow sand
#

theres 5 scirpts should i send them all

astral falcon
#

Upload those, where your debugging logs stop to work

burnt vapor
#

Why not a single place?

willow sand
#

there 1 that controls the state and one that iniciates the collider contact and then there 3 other one handeling the states