#💻┃code-beginner

1 messages · Page 548 of 1

buoyant perch
#
using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    [SerializeField] float moveSpeed;
    [SerializeField] float jumpPower;

    private bool isGrounded;

    // Refrences
    private Rigidbody2D rb;
    private Animator animator;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponentInChildren<Animator>();
    }

    private void Update()
    {
        Debug.Log($"IsGrounded: {isGrounded}");
    }

    private void FixedUpdate()
    {
        HandlePlayerMovement();
        HandleJumping();
        HandleFlipping();
        HandleAnimations();
    }



    private void HandlePlayerMovement()
    {
        float moveInput = 0f;

        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            moveInput = moveSpeed;
            animator.SetBool(Constants.IS_RUNNING_ANIM_STRING, true);
        }
        else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            moveInput = -moveSpeed;
            animator.SetBool(Constants.IS_RUNNING_ANIM_STRING, true);
        }
        else
        {
            moveInput = 0f;
            animator.SetBool(Constants.IS_RUNNING_ANIM_STRING, false);
        }

        rb.linearVelocity = new Vector2(moveInput, rb.linearVelocity.y);
    }

    private void HandleJumping()
    {
        if (isGrounded && (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow)))
        {
            rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpPower);
            isGrounded = false;
        }
    }

    private void HandleAnimations()
    {
        animator.SetFloat(Constants.Y_VELOCITY_ANIM_STRING, rb.linearVelocity.y);
        animator.SetBool(Constants.IS_GROUNDED_ANIM_STRING, isGrounded);
    }

    private void HandleFlipping()
    {
        if (rb.linearVelocity.x > 0)
        {
            transform.localScale = new Vector2(Mathf.Abs(transform.localScale.x), transform.localScale.y);
        }
        else if (rb.linearVelocity.x < 0)
        {
            transform.localScale = new Vector2(-Mathf.Abs(transform.localScale.x), transform.localScale.y);
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag(Constants.GROUND_TAG) && rb.linearVelocity.y <= 0)
        {
            isGrounded = true;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag(Constants.GROUND_TAG))
        {
            isGrounded = false;
        }
    }

}

hi can anyone help with this im trying to be able jump only when i hit the ground but sometimes, when i still touch the ground isGrounded gets set back to false which is the issue, but i dont know why.

visual linden
# buoyant perch ``` using UnityEngine; using UnityEngine.InputSystem; public class Player : Mon...

Try being a bit more generous with the && rb.linearVelocity.y <= 0) check. Eg rb.linearVelocity.y < 0.01f because it can sometimes get stuck hovering around really small values due to how the physics work.
I'd also put some breakpoints or debug logs in the different methods to try to get more clarity into why exactly it's either incorrectly setting isGrounded to false or not correctly setting it to true.
edit I actually don't know why you're checking the velocity at all 🤔 If you enter the ground trigger - surely you are grounded, no?

glossy eagle
#

Hi. One question, if I have a method that is something like

public GenericMethod<T>(T param)
{
  Debug.Log(typeof(T);
}

and I want to have an array of different values for T, how would I do that? What would that array "type" be? Like let's say I have a for loop that loops through an array with different values for T, and I want to use that different value of T for every loop. Something like this:

for (int i = 0; i < PossibleSnapshotInfoTypesArray.Length; i++)
{
  GenericMethod<PossibleSnapshotInfoTypesArray[i]>();
}

In this case, how would I make the PossibleSnapshotInfoTypesArray variable if that's possible?

glossy eagle
#

and then to create the array what do I have to enter there? Something like this?

var PossibleSnapshotInfoTypesArray = new (string, object)[]
        {
            ("pos", PhysicsSnapshotInfo)
        };

("PhysicsSnapshotInfo" is the name of a class)

languid spire
#

so thats a Tuple array and you would add to it using
("pos", new PhysicsSnapshotInfo())

glossy eagle
#

ahhhh okay

#

thanks

#

and then I thought I could just do

GenericMethod<PossibleSnapshotInfoTypesArray[i].Item2>(); 

but that gives an error. Any idea why please?

languid spire
#

yes, you cannot use a variable in place of a generic type

glossy eagle
#

ah

#

then I don't know how to fix it😅

languid spire
#

you do not need the generic if you do

public GenericMethod(object param)
{
  Debug.Log(param.GetType());
}
glossy eagle
#

like basically what I want to make is be able to use JSON deserealize with different types, so I have the method that I cannot change that is

JsonConvert.DeserializeObject<T>()
languid spire
#

Pretty sure JsonConvert has an overide that takes a Type instead of the generic

glossy eagle
#

ohhh okay I see it. Thank you so much 😄

languid spire
glossy eagle
#

yeah I changed that

severe onyx
#

I'm wondering about the best way to store data in a way that other scripts can globally access it. like for enemies. if I want a spawner to spawn a random selection, what would be the recommended way to expose that data to the spawner? The main approach I can think of is make each of them into a prefab, give the spawn script a public list and drag in all prefabs manually, but that doesnt feel like the right answer

#

I guess a similar question applies to a list of classes that share a parent; if I want some other script to randomly pick a weapon Id like it to have access to all scripts that inherit from the weapon script without turning each one into a prefab

cosmic dagger
hexed terrace
#

Use Scriptable Objects to hold data, then you only have 1 prefab and swap the data

real tinsel
#

hey everyone, im not sure if this is the right channel but does anyone know why I can't edit my script in jet brains rider? instead of the normal cursor ive got this block on my text and can't edit anything? cheers

real tinsel
cosmic dagger
burnt vapor
#

Oh, that's usually the reason. Idk then

severe onyx
#

will look into it, ty

hexed terrace
verbal dome
#

Sounds like home key behaviour

hexed terrace
#

VS has an indicator in the UI to show that you've got the insert mode enabled, you can press this to toggle.. does Rider have similar? Look around the UI

real tinsel
#

oml my num lock was toggled 😂

#

thank you

#

been struggling for like half an hour 😭

cosmic dagger
severe onyx
# cosmic dagger SOs can hold data during runtime. use an SO asset (that holds a list) as a varia...

I get the idea in concept but I'm a little confused about the actual implementation here. The way I understood SOs to be used so far would imply I:

  1. create a scriptableobject-script that has nothing but a list
  2. create an instance of the SO in the asset folder
  3. fill the list of that instance with... what exactly if not prefabs?
  4. create a variable for the scriptableobject-script from step 1 in some other script I wanna access the list in and then drag the instance I created in 2 in as a reference

so I dont really understand how that solves the problem Im having at all, I feel like Im missing something basic here

cosmic dagger
#

so the enemy script will have a reference to the SO asset as well . . .

severe onyx
#

no no. I dont need a list of spawned enemies. I need a list of all enemy types that exist to pick from for spawning

cosmic dagger
#

that is one option. the other is the spawner itself will add the enemy to the list after spawning, so the enemy doesn't need a reference to the SO asset . . .

cosmic dagger
verbal dome
#

Do you need to automatically generate a list of the child types deriving from weapon?

severe onyx
#

the spawner needs to be aware of each different enemy that I created outside of the running game, in the editor. I wanna know if there's a better way to let it know which exist other than turning them all into a prefab and dragging all prefabs into a list yknow

verbal dome
#

Gameobjects in the scene?

cosmic dagger
severe onyx
#

ok fair enough

verbal dome
#

and dragging all prefabs into a list yknow
This part you can automate with some editor scripting if you want

#

Like storing them all in list on a SO asset automatically

severe onyx
#

the list itself could be an SO I suppose if I want it to be easily accessible and modified across different scripts without them all talking to each other though?

verbal dome
#

Yeah, you can use SO as a "database"

severe onyx
#

that definitely seems useful, ty

cosmic dagger
#

true, you can automate that if you want. e.g., a button or a method you can call from the editor to find and populate the list with prefabs that derive from a class . . .

severe onyx
#

database is exactly the use case I was looking for I guess

cosmic dagger
severe onyx
#

so if I add an enemy I just add it to the SO asset instead of changing values on the spawner gameobject directly yknow

cosmic dagger
#

they work well because you can use the SOs across scenes without a need to reference . . .

severe onyx
#

yeah thats a huge boon

#

Im thinking if I got, like, 20 different swords that use the same logic but with different values then I turn the sword class into a SO and create 20 different assets of it where I fill in the values, aye?

#

like. creating a new class that inherits from sword for every single one seems insane. but if the logic is the same I realise I could just create a prefab for each one and adjust the values there. and Im wondering if SOs arent the more elegant solution here as well?

cosmic dagger
severe onyx
#

interesting. I was thinking more of having modifiers in the parent object that I change at runtime. eg get a buff that doubles your atk-speed -> set the modifier for atk-speed in the instance of the sword-class without touching the base atk-speed data it pulled from the SO

cosmic dagger
#

you'll find that using composition over inheritance works better with Unity. you want to avoid creating large inheritance chains. they'll drag you down . . .

severe onyx
#

yeah wanting to avoid them is precisely why Im asking these questions

cosmic dagger
severe onyx
#

I guess I was imagining a solution where I can attach something equivalent to an SO directly to a gameobject

#

or am I just back to using prefabs at that point

swift crag
#

You can store the immutable characteristics of an item in an asset, then store:

  • a reference to the asset
  • a list of modifications

on your runtime item object (which could just be a plain class, rather than being a MonoBehaviour that you have to attach to a game object!)

severe onyx
#

ultimately I still need a gameobject to communicate all that data to though if I want a visual representation

swift crag
#

Right, you'll have a game object with renderers and other components to display the item

severe onyx
#

so that trips me up rn, if there's an efficient solution for that without just turning them all into prefabs anyways

swift crag
#

I was poking at a soulslike game a while ago. I had item definition assets that stored things like the name and the item's stats

#

The asset also referenced a prefab, which was the actual physical object you'd see in-game

#

It was possible for multiple items to use the same prefab (think about 30 kinds of potion that all use the same model, just with different colors)

#

The item definition was referenced by the actual Item class, which represented a single instance of that item. Modifications to the item were stored on this class.

severe onyx
#

right. so in my case we'd have the sword SO, 20 different SO assets, and the sworditem monobehaviour attached to one universal prefab, yeah? modify the prefab instance at runtime with data read from the SO asset I wanna use at the time and I got what Im looking for basically?

swift crag
#

in short:

  • Item: A thing in your inventory
  • ItemDefinition: A blueprint for an item
  • ItemProp: A physical object that shows up in the game when you use an item
#

Item points at ItemDefinition and ItemDefinition points at ItemProp

cosmic dagger
severe onyx
#

ooooh

swift crag
#

That's also a decent idea -- you might realize that:

  • Things that you can change when designing an item
  • Things that the player can change in-game

overlap pretty well

#

In that case, you could copy the stats from the item template into the item instance

#

This would cause incorrect stats if you changed the template later on, though

#

That's why I'd rather keep modifications non-destructive -- you just store a list of changes

severe onyx
swift crag
#

in the game, I had separate classes for melee weapons, ranged weapons, and consumables. this made me vaguely unhappy

severe onyx
#

I thought I had understood it but now Im unsure again lol

swift crag
#

it might be helpful to rename Item to ItemInstance

severe onyx
swift crag
#

a field holding a type that isn't a Unity object

#

you might see this referred to as a "POCO" -- plain old class object

cosmic dagger
swift crag
#
[System.Serializable]
public class ItemInstance {
  public ItemDefinition definition;
  public string nickname;
}
#

Note that in my example, you are not copying anything from ItemDefinition when you want to put an item in the user's inventory.

#

You're just creating an ItemInstance and pointing it at an item definition

severe onyx
swift crag
#

gah, name collisions

#

that sounds like "item property"

severe onyx
#

no no

#

I get what you mean by that

#

it's a monobehaviour and it's attached to a gameobject

#

this is hurting my brain lol. I may just be bad at abstract thinking

swift crag
#

item and inventory systems are fun

#

I misunderstood you as misunderstanding me :p

severe onyx
#

ok let's try this again

swift crag
#

Here's an example from that game.

please ignore the horrendous exception throwing in the first file 😬

tulip nimbus
#

Debug.DrawLine(transform.position, Vector3.down, Color.red);

How can i make it that the Raycast (Or in this case, Line) goes down from the players position?

swift crag
#

DrawLine draws a line between two points

#

use DrawRay if you want to draw a line from a point in a direction

tulip nimbus
swift crag
visual linden
swift crag
#

note that Raycast doesn't care about how long the vector is

#

See the documentation for the method

tulip nimbus
#

Thank you!

swift crag
#

It uses a separate maxDistance argument

visual linden
#

transform.position + Vector3.down * length

swift crag
#

So make sure that, if you use DrawRay, you multiply your normalized direction by the max distance you provide to the Raycast method

#

transform.down is good if you care about the player's own "down" direction, rather than the world -Y direction

#

this is relevant if the player rotates

visual linden
tulip nimbus
#

Ah i see

tulip nimbus
stark flame
#

I’ve got a problem , I have a game where a ball is getting generated and I want to put on a random spawn interval with Random.Range(3f, 6f); in the invokeRepeating method but I don’t actually know where I should store that random variable

swift crag
#

Should the spawn time get randomized every time the ball spawns?

#

If so, something like this doesn't work

swift crag
#
InvokeRepeating(nameof(SpawnMethod), Random.Range(3f, 6f));
severe onyx
# swift crag `Item` is a serializable class, but it's not a Unity object `ItemDefinition` is ...

ItemProp is a MB on a gameobject and it executes the logic that happens when I press buttons and has a variable of Item
Item is a non MB class that holds all the variables ItemProp uses for that logic
ItemDefinition is an SO that basically just holds Item, assets made from it just change the numbers within Item for different versions of the item
at runtime, I access a list of all the ItemDefinition assets and pull its version of Item to set the field of Itemwithin ItemProp so it knows which values to use?

swift crag
#

This picks one random number and you're stuck with it forever

#

Consider having the spawn method invoke itself at the end, or using a coroutine so that you can do this

#
while(true) {
  Spawn();
  yield return new WaitForSeconds(Random.Range(3f, 6f));
}
cosmic dagger
stark flame
swift crag
#

Show the actual error

#

I'm guessing you're trying to do this

#
private float random = Random.Range(3f, 6f);
swift crag
stark flame
#

UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor( or instance field initializer), call it in Awake or Start instead , called from MonoBehaviour ‘SpawnManagerX’

swift crag
stark flame
swift crag
#

This also wouldn't be very useful, since you'd just have one random number forever..

severe onyx
swift crag
stark flame
swift crag
#

!code

eternal falconBOT
severe onyx
#

because otherwise Ill list all the same variables in Item and ItemDefinition and copy them over in code basically, yeah?

sonic plover
#

yo

severe onyx
#

like obviously it would work either way, Im just wondering what's prettier

swift crag
#

I would prefer to calculate the values as needed. I wouldn't copy ItemDefinition.damage into Item.damage

#

I'd give Item a property that calculates the damage based on the definition's stats and any customizations we've made

#
public ItemDefinition definition;
public float extraDamage;

public float Damage => definition.damage + extraDamage;
#

very loosely

severe onyx
#

oh okay. I kinda thought that was going into ItemProp I guess

swift crag
#

There is a lot of wiggle room here

#

I would want the ItemProp to just ask its Item "hey, how hard do I hit?"

#

and then the Item asks the ItemDefinition "how hard does this thing normally hit?"

#

then it sprinkles on any modifiers and hands the result to the prop

stark flame
# swift crag Show your code, please

using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

public class SpawnManagerX : MonoBehaviour
{
public GameObject[] ballPrefabs;

private float spawnLimitXLeft = -22;
private float spawnLimitXRight = 7;
private float spawnPosY = 30;

private float startDelay = 1.0f;



// Start is called before the first frame update
void Start()
{
    InvokeRepeating("SpawnRandomBall", startDelay, Random.Range(0f, 6f));
}

// Spawn random ball at random x position at top of play area
void SpawnRandomBall ()
{
    
    int ballIndex = Random.Range(0, ballPrefabs.Length);
    // Generate random ball index and random spawn position
    Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);

    // instantiate ball at random spawn location
    Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);
}

}

swift crag
severe onyx
#

massively simplified lol

swift crag
#

In my code, I have a whole "Hitbox" and "Hurtbox" system to handle the actual detection

severe onyx
#

ok gotcha

swift crag
#

a Hitbox notices an overlap and tells the Weapon about it

#

(see the Contact method)

severe onyx
#

yeah the hit detection stuff is a can of worms Ill open another day

swift crag
#

there are also Blockboxes to handle blocking and parrying

#

well, I wound up pivoting to bloodborne style parrying, so that became irrelevant

#

garme design

severe onyx
#

generally, it's not efficient to do collision.collider.getcomponent<whateverhandlestakingdamage> though right?

swift crag
#

At some point you have to do that

stark flame
# swift crag please read the bot message

cs

using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

public class SpawnManagerX : MonoBehaviour
{
public GameObject[] ballPrefabs;

private float spawnLimitXLeft = -22;
private float spawnLimitXRight = 7;
private float spawnPosY = 30;

private float startDelay = 1.0f;



// Start is called before the first frame update
void Start()
{
    InvokeRepeating("SpawnRandomBall", startDelay, Random.Range(0f, 6f));
}

// Spawn random ball at random x position at top of play area
void SpawnRandomBall ()
{
    
    int ballIndex = Random.Range(0, ballPrefabs.Length);
    // Generate random ball index and random spawn position
    Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);

    // instantiate ball at random spawn location
    Instantiate(ballPrefabs[ballIndex], spawnPos, ballPrefabs[ballIndex].transform.rotation);
}

}

swift crag
stark flame
#

I’ve not got those ‘ on my keyboard

swift crag
#

```

cosmic dagger
swift crag
swift crag
# swift crag At some point you *have* to do that
    void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent<Blockbox>(out var blockbox))
        {
            weapon.Contact(this, blockbox);
        }
        if (other.TryGetComponent<Hurtbox>(out var hurtbox))
        {
            if (weapon.entity != hurtbox.entity)
                weapon.Contact(this, hurtbox);
        }
    }
#

TryGetComponent is marginally better because it doesn't allocate a bogus object if it can't find anything

#

the result will be a genuine null

#

instead of an invalid unity object

runic lance
#

it only allocates in the editor though

swift crag
#

yeah, that's true

#

the main advantage is that it makes your intentions more obvious

#

if I can find X, then ...

cosmic quail
swift crag
#

You have posted the same messsage three times now..

swift crag
stark flame
#

Site *

swift crag
#

Paste your code into the text box and click "Paste it!"

stark flame
#

Can’t you read it like that ?

swift crag
#

it takes up a lot of space in the chat, which is why we really want people to use paste sites for larger amounts of code

cosmic dagger
#

you literally just copy your !code into any of the sites, click save/paste (or whatnot) and send us the link . . .

eternal falconBOT
swift crag
#

(well, two out of five of the sites are down right now, oops)

stark flame
ancient hamlet
#

I have a question about implementation: what is the main idea behind hero based games (like MOBAs, AutoBattlers, etc...) that have specific skills for each hero? Do I try to break down the skills into their components of what they do and inherit them or do I create a single class for each skill ?

swift crag
#

then log in to discord on your computer.

fickle plume
swift crag
#

You can try to break skills down into composable pieces

stark flame
swift crag
#

but you'll probably wind up with so many complex interactions and edge cases that it's not worth doing

stark flame
#

Because I’ve not got discord on my pc

swift crag
#

Discord has a web client. Use it.

fickle plume
cosmic dagger
ancient hamlet
cosmic dagger
ancient hamlet
stark flame
#

And send yall

fickle plume
#

@stark flame Stop talking about it and just do what you were asked.

#

@stark flame Why would you paste the same thing again?...

stark flame
#

and then copied it as idk what to do next

fickle plume
cosmic dagger
cosmic quail
runic lance
ancient hamlet
#

each with a unique skill

cosmic quail
ancient hamlet
cosmic dagger
fickle plume
cosmic quail
#

oh true, yeah in that case a separate script for each would be bad yeah

stark flame
# fickle plume You should add your question as well.

... , I'd like to store the randomization into a variable and then fill the variable's name into the invokeRepeating(),but I don't really know where to put , i already tried in the SpawnRandomBall() and it doesnt work

cosmic quail
#

i never knew that

stark flame
#

such as if it was in an Update() method

pseudo dirge
#

Hi guys, can you tell me how can I spawn a prefab at a point I want on the x and y axis, but without creating separate gamobjects for it? I tried to use an array where I put the points I need and added them to the vector, but the prefab spawns on the center of the vector

fickle plume
stark flame
#

each time

fickle plume
#

From the range it can execute every 0 seconds i.e. every frame

#

What do you actually want to do?

stark flame
fickle plume
#

Why are you posting this in a code channel?

ancient hamlet
#

sorry I thought it involved code at some point, plus beginner question

#

I moved it

pine bone
#

Hello, i'm creating enemies for my 2d platformer game and i want to ask whats the best way to code unique enemy mechanics? Should i create a base enemy class and inherit from there? Whats the eaisest way that i can add various enemy types without having to rewrite a lot of the code

ancient hamlet
fickle plume
#

Also you should use Coroutine for repeated actions to have more control.

pine bone
stark flame
#

i already tried putting this variable outside any functions and it does the same its actually doing rn

stark flame
fickle plume
stark flame
#

anyway thanks @fickle plume ;ill figure out how to do it by myself

fickle plume
ancient hamlet
# pine bone how can i use interfaces for this?

something like this

public interface IUnit
{
    string Name { get; }
    int Health { get; set; }
    int Attack { get; }
    int Defense { get; }
    void TakeDamage(int damage);
    void Move(Vector3 targetPosition);
}

then you just

public abstract class UnitBase : IUnit
{
  ...
}

now you have a base class for every new enemy so you dont need to start from scratch~

ancient hamlet
polar acorn
#

Give it the position you actually want

deft ridge
#

Hi! I'm making a fighting game project in Unity and I've coded in the movement and reading inputs. Now I want to start adding visuals like the background and actual character sprites. I'm having an issue where I added a background but it still shows the white space behind it. If I increase the size of the image it'll become blurry which I want to prevent. I'm not sure if the problem if the problem is the size of the background image or the size of the other objects and camera in the scene. How can I fix this? Here's the camera script i made as well in case that contributes in any way: https://pastecode.io/s/zuy4tq0v

pine bone
stark flame
#

Omg , thanks a lot bro

fickle plume
#

@visual linden don't post LLM generated answeres on the server.

visual linden
fickle plume
#

Next time I will ban you then

stark flame
#

@fickle plume can’t you get back the code in logs please

#

I had no time to check it

fickle plume
#

@stark flame You can lookup coroutines example in the manual

visual linden
#

I don't even know what to say, this is hilarious.

ancient hamlet
#

can I script my way into generating game data as scriptable objects files from a serializable filetype (json, speadsheet) or is that a janky solution?

#

im setting each single value by hand in the editor, it gets job done but takes some time

fickle plume
rough lynx
#

Sorry it just seems like a bit of an unenforacble rule maybe I shouldn't start something here

fickle plume
rough lynx
#

I read the community conduct to see if it was a rule and it was so fair play but it's not like there's really a way to enforce it considering there's no way to prove a message is AI generated unless told so

polar acorn
rough lynx
#

Well this person is claiming their message was flagged as LLM generated after it got deleted so it could be

#

Sorry I could've worded that better it seemed a bit like a snide remark against Fogsight

fickle plume
#

@rough lynx Ban remark was response to their trolling.

rough lynx
#

Woahh wtf

fickle plume
#

!ban 489595006454333440 Spam

eternal falconBOT
#

dynoSuccess c0nd3v was banned.

burnt vapor
#

!code testing

eternal falconBOT
burnt vapor
#

hatebin is now also down

swift crag
#

I was just typing a message about how I thought Fogsight was being a little too harsh

#

However,

#

that was an interesting response

rough lynx
#

I'm guessing you're on about the person who joined just to call them a slur

burnt vapor
#

Two of the five sites are down now

rough lynx
#

Dang that's rough

#

I thought you meant down as in maintenance or issues down not gone

fickle plume
swift crag
#

It could be a temporary thing

#

But gdl.space has been borked for a while

burnt vapor
swift crag
#

hatebin was completely dead for a bit, and now it's a default startup page

polar acorn
rough lynx
#

Oh...

#

I clicked on hatebin thinking it was hastebin

burnt vapor
#

Sadge, hatebin and gdl.space were my favourite

polar acorn
swift crag
#

gdl.space was my go-to, yeah

rough lynx
#

Why hatebin and gdl.space? Where they any different to something like hastebin?

#

And why not just pastebin?

burnt vapor
#

I liked how straight to the point they were

#

Nothing but a straight up paste with proper highlighting

polar acorn
rough lynx
#

Yeah I mean it's not exactly drag and drop since you have to select the syntax highlighting but it's cool aside from that

polar acorn
#

No syntax highlighting, 80% of the page is ads, it has a fucking algorithm. Suggestions for dumps of text! Such a bloated garbage website

rough lynx
#

Dang I didn't see the ads bit since I'm an adblock user

#

And I don't think I've had suggestions but I dunno if that's my browser blocking "creepy stuff" as it calls it

polar acorn
#

Trying to read a pastebin in mobile is like playing Where's Waldo with code

rough lynx
#

Lmao

#

Oh god yeah I just turned off the blocker and I've got 4 ads and one that scrolls with me at the bottom

pseudo dirge
#

Friends, why can't I link to the second script when connecting it as a component? Unity doesn't even see it.

polar acorn
pseudo dirge
polar acorn
pseudo dirge
# polar acorn So you're trying to add a reference to itself?

Now I'm working on the logic that when you press the button potions fall out of the bucket, I need them to fall out according to the cells that I set in another script.
The other script has an array of these cells and adds the bucket itself at startup.

polar acorn
pseudo dirge
polar acorn
pseudo dirge
#

Spawn Item is on the prefab, which is created at game startup. It is from this prefab that I am trying to call the Spawn Tool

shadow rain
#

how do i disable a script from another script?

#

bc ive got this

#

more enable the script ig

pseudo dirge
# polar acorn Prefabs cannot reference in-scene components. You will need to set that variable...

Would it be better to separate the cage script, from the prefab creation? Do I understand correctly that if the tool will be inherited from the array with cells, then the tool can become a parent for potions and then when I click on the tool I will be able to distribute potions to the cells? Sorry for stupid questions, I'm just learning to program and I'm not very familiar with oop principles.

polar acorn
polar acorn
shadow rain
#

no i wawnt it to be enabled mb

#

i shouldve said

#

thats the error as well

pseudo dirge
polar acorn
dusty ember
#
UnityEditor.Graphs.Edge.WakeUp () (at <d38a7573bc684cda95a248e6e5884edc>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <d38a7573bc684cda95a248e6e5884edc>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <d38a7573bc684cda95a248e6e5884edc>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <d38a7573bc684cda95a248e6e5884edc>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <d38a7573bc684cda95a248e6e5884edc>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <d38a7573bc684cda95a248e6e5884edc>:0)

what does this even mean?? I cant find anything to fix it

tropic sundial
polar acorn
fickle plume
#

Also in general posting entire solutions is not great for learning as well.

swift crag
tropic sundial
#

Was the code not directly helping the person being replied to? You said there was helpful comments for each line?

swift crag
#

it's usually very obvious, because the code is stuffed with unnecessary comments

#

i don't actively search for it or anything

languid spire
queen adder
#

Can someone help me with a Unity 2D script?

polar acorn
polar acorn
#

you have to actually ask a question

cosmic quail
frosty hound
#

Let me break down my sentence for you in a way that might be easier to understand:

#
  1. You have to explain your issue. This means you have to explain your issue.
  2. You have to show your code. This means showing your code

And then do so in this channel, which is for beginners and code.

queen adder
#

then can i post here?

#

public class TeleportObject : MonoBehaviour
{
    public DoorTrigger doorTrigger;  // Referência ao script DoorTrigger

    public GameObject objectToTeleport;  // O GameObject a ser teleportado (Player ou outro)
    public Transform teleportPoint;  // O ponto para onde o GameObject será teleportado

    private void Update()
    {
        // Verifica se a variável DoorOpen é verdadeira no script DoorTrigger
        if (doorTrigger != null && doorTrigger.DoorOpen)
        {
            // Teleporta o GameObject para a posição do TeleportPoint
            objectToTeleport.transform.position = teleportPoint.position;

            // Reseta a variável DoorOpen para impedir que o teleporte aconteça repetidamente
            // Isso garante que a porta só será aberta uma vez
            doorTrigger.DoorOpen = false;  // Mantém a funcionalidade do DoorTrigger
        }
    }
}

cosmic quail
swift crag
#

give them a moment :p

frosty hound
#

NRE on objectToTeleport is my guess

queen adder
#

my problem is: this script destroy the effect of other script

frosty hound
#

This script has no code that suggests it's destroying anything. What effect, what script?

#

The DoorTrigger object? Is there an effect playing that only happens when DoorOpen = true?

swift crag
#

they probably mean that another component stops working correctly

#

"destroy the effect"

queen adder
#

DoorTrigger is the script

#

and the effect of him is Teleport Player to X, Y, Z

frosty hound
#

Well, your code will only teleport the object once, because it sets doorTrigger.DoorOpen = false after it does, which fails the condition in the if statement since that looks for it to be true.

queen adder
#

ammm

#

ill try fix this

frosty hound
#

Assuming that's the issue, you need to, at some point, open the door again on your doorTrigger blobnod

livid sable
#

Hello, can anyone help?

short hazel
#

Not if you don't ask a question :)

livid sable
#

oh sorry

cosmic quail
shadow moon
#

how is Quaternion.LookRotation supposed to work in 2d without my sprites turning into 1d lines then breaking lmao

verbal dome
shadow moon
#

yes

verbal dome
#

It has a default of Vector3.Up. It makes sense in 3D

#

But in 2D you should use Vector3.back I think

shadow moon
#

the perspective of the game is birds eye

verbal dome
#

Anyway, are you just trying to make a gameobject look at something in 2D?

shadow moon
#

rotate towards the player slowly yes yes

verbal dome
#

If you want instant rotation you can do transform.right = direction or transform.up = direction
But since you want it to happen over time you should probably get the direction's angle and rotate the player towards that angle

#

The Z axis angle, that is

shadow moon
#

i currently use ```cs
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(TargetPos, Vector3.back), Agility * Time.fixedDeltaTime);

verbal dome
#

Yeah I don't think that's very robust in 2D since you would only want to rotate on the Z axis

#

This could rotate on other axes too

shadow moon
#

yeah im not seeing an easy solution here

verbal dome
#

I suggest this:
-Get a direction from A to B
-Use Vector2.SignedAngle(Vector2.up, direction) to get an angle
-Use Mathf.MoveTowardsAngle in Update with transform.eulerAngles.z

#

Another way would be
-Get a direction from A to B
-Set the direction's Z value to zero
-Assign the direction to transform.forward or transform.right

swift crag
#

Yep, that sounds reasonable.

#

Quaternion.RotateTowards is good if you need a 3D rotation, but there's no reason to use it here -- we only have one angle!

wintry kiln
#

Hello im trying to develop a 2d platform game and im having some trouble in the "door" part (like changing the rooms etc.). I cant seem to understand how to transport the player from a scene to the other and I was wondering if anyone was willing to help me or send me a tutorial that shows how its done

swift crag
#

So there are a few ways to do this

#

You can make each room into its own scene without a player object

#

You can put the player in a special scene that never gets unloaded using the DontDestroyOnLoad method.

#

Now you can load a new scene, then move the player into the right spot afterwards

#

You could also put a player object in every room, and just throw out the old player completely when changing scenes.

#

You'd have to store stuff like health separately from the player object in that case

#

You could also have a single scene and a bunch of room prefabs. When you change rooms, you destroy the old room and instantiate the new room

vestal spruce
#

@fickle plume they are grumbling about it and trying to cayse drama on the reddit now. Very good behaviour.

fickle plume
#

Spoonfeeding someone an answer is not helping. They did that before as well. Also reminder there's no off-topic here.

#

!warn 658564384754237440 Now I know you are doing this on purpose. And seeing as you have no constructive activity on the server, next off-topic remark will result in ban.

eternal falconBOT
#

dynoSuccess omegafoamy has been warned.

gloomy vine
#

Whaaat xD

young mason
#

@fickle plume not cool

fickle plume
#

!ban 658564384754237440 Ignoring warnings. Trolling.

eternal falconBOT
#

dynoSuccess omegafoamy was banned.

visual linden
# fickle plume Spoonfeeding someone an answer is not helping. They did that before as well. Als...

Let's be clear. I didn't spoonfeed anyone anything. You guys were telling them they needed to use coroutines, and I just explained how coroutines worked and showed how they could be used to do what they were trying to do. Their response of "Omg thank you" to my one post vs the 20 or so back and forths you had with them should tell you all you need to know about the worth you contribute to this world.

gloomy vine
#

That wasnt trolling, what are you talking about

digital violet
#

Yo

fickle plume
fickle plume
young mason
digital violet
#

som1 fill me in, what's the drama XD

#

you can't spoonfeed?

fickle plume
short perch
#

Why doesn't this work?


transform.rotation = Quaternion.Euler(Angle, 0, 0);```
#

it doesn't give an error, it's just not rotating like it should

frosty hound
#

@digital violet Don't drag it here please, if you aren't asking questions or helping people, please don't post, thanks.

digital violet
#

mate

#

delete all these comments?

#

ur own mod is dragging it out?

#

So delete that too

#

shouldn't everyone stick by the rules

#

or is it 1 rule for mods, another for everyone?

#

so instead of deleteing my messages calling a mod out, delete everyone else's who's dragged it out?

frosty hound
#

They're responding to the comments, in the thread.

rich adder
digital violet
#

they just started that

polar acorn
#

Hi reddit

frosty hound
#

If you want to join them, please use the thread.

#

Leave this channel for people needing help/receiving help, thanks.

polar acorn
digital violet
polar acorn
#

Were they in a thread

frosty hound
#

Don't spill it out here please.

digital violet
#

there was no thread when i posted my messages hahahaha

steep rose
#

I thought you guys dropped it

polar acorn
digital violet
#

tell all of these people to make 1?

valid vector
#

cloesd everything

digital violet
#

I'm not a thead maker

#

lmfao

frosty hound
valid vector
#

thank

polar acorn
digital violet
#

anyway, i'll drop it

#

wont respond to any1 else 😄

wind raptor
#

I cannot seem to figure out how to make the build not automatically be full screen, and I don't know how to make it windowed/resizeable. I have added this code in one of my scripts, but it doesn't seem to do anything when I press F11:
if (Input.GetKeyDown(KeyCode.F11)) Screen.fullScreen = !Screen.fullScreen;

In my player settings, Full screen mode is set to Windowed, and Resizable Window is ticked.

polar acorn
#

I think it remembers what state it was when it last closed? The Windows shortcut for toggle fullscreen on any application is Alt+Enter. Try using that to make it windowed and see if it remembers? The code could have an unrelated problem

violet agate
#

i think i broke my unity idk what to do now

hexed terrace
polar acorn
eternal falconBOT
hexed terrace
#

Is it the UdonSharp that points to VRChat ?

polar acorn
#

Ah, right, that's just an error saying there's other errors.

#

That shader could be from somewhere else

#

I don't think ShaderGraphZ is part of the SDK

wind raptor
polar acorn
#

If not, then we can try to figure out why the window isn't changing

wind raptor
#

Alright well, an apparently relevant detail is that I'm using multiple displays. At the program's start, I set all of the connected displays active. When I comment out that line of code, the full screen toggle does work, but now I only have the one display visible.

#

K, from what I'm reading, it's not possible to have multiple windows for a single application

wary sable
#

Yeah generally you’d have to extend it the width/height of all the displayes. Unfortunately because people can have monitors of all shapes and sizes you are limited to the smallest they have plugged in

cosmic charm
#

I'm trying to make a 2 players game and I reached this point.
but the thing I'm struggling to make the character's controls different, should I rewrite the player code in different keys, or is there a smart way to do that

I tried to implement the new Input system to my game and I failed, couldn't figure out how

any help would be appreciated <3

frosty field
#

best way to create "onGround" bool? someone told me to use raycast but im curious if there is better methods

frosty field
#

well collision does work but it returns true even if im touching a wall

steep rose
frosty field
#

so it allows player to doublejump while not being on ground

cosmic charm
steep rose
frosty field
#

well

#

you did i think

#

but you told me to use raycast which i dont really understand how it should work

thorn oyster
#

best way to create "onGround" bool?

steep rose
#

it is 1 line of which you need to do

cosmic charm
#

@frosty field The collision should be a bit lower than the character collision itself

steep rose
#

unless I am missing something

quasi dawn
#

Otherwise it'll be false

polar acorn
polar acorn
steep rose
polar acorn
#

The rest is just filtering on which kinds of things count

swift crag
#

2D non-allocating physics methods can fill a list with values, instead of requiring a fixed-size array. It's a lot more convenient

#

(obviously, allocation is possible if the list has to grow, but that won't happen over and over)

frigid sapphire
#

I am making a clicker, very new to unity. When making an autocursor, the balance goes up way too fast, is there a way to slow it down?

eternal juniper
polar acorn
frigid sapphire
frigid sapphire
#

Or only a small part?

eternal falconBOT
polar acorn
#

Note, gdl space and hatebin are down at the moment, use one of the other three

#

!code

eternal falconBOT
frigid sapphire
#

A little sphaghetti code but it shouldn't be that bad

swift crag
#

this indentation 😭

#

the first thing that sticks out to me here is the variable names

#

p1 and p1d aren't very obvious

#

i'd just call them price1 and price1Display, at least

frigid sapphire
#

Noted

polar acorn
swift crag
#

as for the rapid income

#

yeag

polar acorn
#

This is literally identical to add acm in Update

swift crag
#

it'll randomly skip frames

#

but it's very close to just slamming that in Update

polar acorn
#

1 * Time.deltaTime is literally the definition of "a frame"

swift crag
#

Why did you do that? Not trying to make you feel dumb :p

wintry quarry
#

If the next frame is shorter than the previous frame, it will skip at least one frame

polar acorn
#

deltaTime is the amount in seconds the frame took to render. If you're waiting that long, that's ust going to wait a frame

wintry quarry
#

it's going to be entirely inconsistent

frigid sapphire
#

So what I thought would happen is that the WaitForSeconds would allow me to change the delay between each income

polar acorn
#

Along with added inconsistency if the framerate fluctuates yeah

polar acorn
#

If you want it to wait longer than that, you'll need to give it a bigger number to wait

frigid sapphire
#

Yeah I tried WaitForSeconds(5 * deltaTime) but it barely changed

swift crag
#

WaitForSeconds(1f) would be more reasonable

polar acorn
swift crag
#

why are you factoring in deltaTime here?

swift crag
wintry quarry
#

hoenstly using a coroutine here is a mistake if this is some kind of simulation

polar acorn
#

That's not a huge difference from one frame in the grand scheme of things

#

How long do you want to wait between ticks?

frigid sapphire
#

Around 1-2 seconds

swift crag
#

in that case, just wait for one second!

polar acorn
swift crag
#

Note that this is still going to be problematic. WaitForSeconds(1f) will wait for a little longer than one second, since the coroutine is only going to resume on the frame after at least one second has passed.

polar acorn
#

So give it the number you want

swift crag
frigid sapphire
#

So I changed the wait time to 5f but from what I see is that it just delays when the loop starts and not how often the payout occurs

swift crag
#

This makes sure that, even if you have a very small interval, you get the correct amount of money

polar acorn
rare basin
#

can anyone help restoring this window? i have somehow disabled it, it doesnt appear anymore even with gizmos enabled, particles selected in the hierarchy

polar acorn
#

Coroutines run up until they hit a yield, then pause for however long it is supposed to, then resume from where they left off until they either hit another yield or the function ends.

#

yield break being "End the coroutine early"

polar acorn
rare basin
#

yes i did

frigid sapphire
rare basin
#

even restarting pc and unity :/

#

also cant find any info about it in the internet

polar acorn
frigid sapphire
polar acorn
#

usually a while loop with some sort of exit condition. It won't be infinite as long as there is a yield inside the loop

hearty hamlet
#

anyone know why the ray isnt being fired, cant see the debug, it prints nothing i dont understand why

polar acorn
#

You only draw the ray if the cast returns true

#

so if it doesn't hit anything, it won't draw anything.

hearty hamlet
#

ok thank you

#

still dont understand why it doesnt hit anything but thats something

#

no i dont think it is being fired

#

doesnt print the else statment either

#

oh wait it does mb

rare basin
north kiln
polar acorn
icy sluice
#

.interpolation = RigidbodyInterpolation.Interpolate;

the rigidbody 3D doesnt switch to Interpolate

teal viper
icy sluice
#

and general movement its jerky/snippy

#

when i manualy set it to Interpolate its smooth, but than client cant join and set its starting position

polar acorn
#

Put a log after you set it to ensure the function is running

icy sluice
#
Player.GetComponent<NetworkObject>().SpawnAsPlayerObject((ulong) PlayersOnline, true);
        yield return new WaitForSeconds(delay);
        //Player.transform.position = Spawns[PlayersOnline].position;
        Player.GetComponent<ArcadeVehicleController>().carBody.position = Spawns[PlayersOnline].position;
        Player.GetComponent<ArcadeVehicleController>().rb.position = Spawns[PlayersOnline].position;
        PlayersOnline=+1;
        Player.GetComponent<ArcadeVehicleController>().carBody.linearVelocity = Vector3.zero;
        Player.GetComponent<ArcadeVehicleController>().rb.linearVelocity = Vector3.zero;
        yield return new WaitForSeconds(delay);
        Player.GetComponent<ArcadeVehicleController>().carBody.interpolation = RigidbodyInterpolation.Interpolate;
        Player.GetComponent<ArcadeVehicleController>().rb.interpolation = RigidbodyInterpolation.Interpolate;
        yield return new WaitForSeconds(delay);
        Player.GetComponent<ArcadeVehicleController>().carBody.isKinematic = false;
        Player.GetComponent<ArcadeVehicleController>().rb.isKinematic = false;

everything but interpolation gets applied

polar acorn
# icy sluice it is running

Then if it's not set in the inspector, either you're looking at a different object or something else is setting it back after this

icy sluice
teal viper
icy sluice
#

i also changed the name of an object when i runned it

teal viper
#

Add the GameObject as the second parameter to the log as well, so that you can confirm in the editor.

teal viper
icy sluice
#

"babaroga"
just what i set it to print

#

now wait

#

now that i have asked for help, it should fix it self in 10min

teal viper
cosmic charm
#
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerControls : MonoBehaviour
{
    [Header("Player Settings")]
    [SerializeField] private PlayerInput playerInput;
    [SerializeField] private int playerIndex;


    public Vector2 MoveInput { get; private set; }
    public bool JumpPressed { get; private set; }
    public bool DashPressed { get; private set; }
    public bool AttackPressed { get; private set; }
    public bool CounterAttackPressed { get; private set; }

    private PlayerInputActions inputActions;

    private void Awake()
    {
        // Create new input actions instance for each player
        inputActions = new PlayerInputActions();
        
        // Get the PlayerInput component
        playerInput = GetComponent<PlayerInput>();
        
        // Set the player index based on PlayerInput
        playerIndex = playerInput.playerIndex;
        
        // Switch control scheme based on player index
        if (playerIndex == 0)
        {
            playerInput.SwitchCurrentControlScheme("Keyboard", Keyboard.current);
        }
        else if (playerIndex == 1)
        {
            playerInput.SwitchCurrentControlScheme("Gamepad", Gamepad.current);
        }
    }

    private void OnEnable()
    {
        EnableAllInputs();
    }

    private void OnDisable()
    {
        DisableAllInputs();
    }

    private void EnableAllInputs()
    {
        inputActions.Player.Enable();
        
        inputActions.Player.Move.performed += OnMove;
        inputActions.Player.Move.canceled += OnMove;
        inputActions.Player.Jump.performed += OnJump;
        inputActions.Player.Jump.canceled += OnJump;
        inputActions.Player.Dash.performed += OnDash;
        inputActions.Player.Attack.performed += OnAttack;
        inputActions.Player.CounterAttack.performed += OnCounterAttack;
    }

    private void DisableAllInputs()
    {
        inputActions.Player.Disable();
        
        inputActions.Player.Move.performed -= OnMove;
        inputActions.Player.Move.canceled -= OnMove;
        inputActions.Player.Jump.performed -= OnJump;
        inputActions.Player.Jump.canceled -= OnJump;
        inputActions.Player.Dash.performed -= OnDash;
        inputActions.Player.Attack.performed -= OnAttack;
        inputActions.Player.CounterAttack.performed -= OnCounterAttack;
    }

    // Input Action callbacks
    private void OnMove(InputAction.CallbackContext context)
    {
        MoveInput = context.ReadValue<Vector2>();
    }

    private void OnJump(InputAction.CallbackContext context)
    {
        JumpPressed = context.performed;
    }

    private void OnDash(InputAction.CallbackContext context)
    {
        DashPressed = context.performed;
    }

    private void OnAttack(InputAction.CallbackContext context)
    {
        AttackPressed = context.performed;
    }

    private void OnCounterAttack(InputAction.CallbackContext context)
    {
        CounterAttackPressed = context.performed;
    }
}

I'm trying to set the controls based on the playerIndex

but it's giving me this error

#

InvalidOperationException: Cannot set control scheme 'Keyboard' by name on user #0 as not actions have been associated with the user yet (AssociateActionsWithUser)
UnityEngine.InputSystem.Users.InputUser.TryFindControlScheme (System.String schemeName, UnityEngine.InputSystem.InputControlScheme& scheme) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Plugins/Users/InputUser.cs:520)
UnityEngine.InputSystem.Users.InputUser.FindControlScheme (System.String schemeName, UnityEngine.InputSystem.InputControlScheme& scheme) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Plugins/Users/InputUser.cs:525)
UnityEngine.InputSystem.PlayerInput.SwitchCurrentControlScheme (System.String controlScheme, UnityEngine.InputSystem.InputDevice[] devices) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Plugins/PlayerInput/PlayerInput.cs:955)
PlayerControls.OnEnable () (at Assets/Scripts/New/Multiplayer/PlayerControls.cs:38)
UnityEngine.InputSystem.PlayerInput:Instantiate(GameObject, Int32, String, Int32, InputDevice)
GameManager:SpawnPlayers() (at Assets/Scripts/New/Joanna/Skills/GameManager.cs:63)

#
using UnityEngine;
using UnityEngine.InputSystem;

public class GameManager : MonoBehaviour
{
    [Header("Player 1 Settings")]
    [SerializeField] private GameObject player1Prefab;
    [SerializeField] private Transform player1SpawnPoint;

    [Header("Player 2 Settings")]
    [SerializeField] private GameObject player2Prefab;
    [SerializeField] private Transform player2SpawnPoint;

    private PlayerInputManager inputManager;
    public static GameManager Instance { get; private set; }

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

        // Get or add PlayerInputManager
        inputManager = GetComponent<PlayerInputManager>();
        if (inputManager == null)
        {
            inputManager = gameObject.AddComponent<PlayerInputManager>();
        }

        // Disable auto-join
        inputManager.joinBehavior = PlayerJoinBehavior.JoinPlayersManually;
    }

    private void Start()
    {
        // Wait a frame to ensure everything is initialized
        Invoke(nameof(SpawnPlayers), 0.1f);
    }

    public void SpawnPlayers()
    {
        // Check if prefabs are assigned
        if (player1Prefab == null || player2Prefab == null)
        {
            Debug.LogError("Player prefabs not assigned in GameManager!");
            return;
        }

        // Clean up any existing players first
        var existingPlayers = GameObject.FindGameObjectsWithTag("Player");
        foreach (var player in existingPlayers)
        {
            Destroy(player);
        }

        // Manually spawn player 1 (Keyboard)
        var player1 = PlayerInput.Instantiate(player1Prefab, 
            controlScheme: "Keyboard",
            pairWithDevice: Keyboard.current);
        player1.transform.position = player1SpawnPoint.position;
        player1.name = "Player1_Keyboard";

        // Manually spawn player 2 (Gamepad)
        var player2 = PlayerInput.Instantiate(player2Prefab,
            controlScheme: "Gamepad",
            pairWithDevice: Gamepad.current);
        player2.transform.position = player2SpawnPoint.position;
        player2.name = "Player2_Gamepad";
    }

    public void RespawnPlayers()
    {
        SpawnPlayers();
    }
}

and this is the game manager

#
  • screaming for help *
teal viper
cosmic charm
#

Ok, thank you

timber tide
#

Should post a paste site too cause can't read any of that on mobile

#

Error to me reads like an incorrect input map asset, or it's not been enabled. Probably find the better answer via google

untold shore
#

Hey, I know this is a little idiotic, but I don't even know where I should look to research how to get this. Currently, I have a card prefab that's going to hold all my sprites, and my sprites are in an array. What I want is that sprite to change based on the array (where itll pick a sprite, that sprite will show up). I have a canvas, but I don't know where to go from there. Do I make an object that the array attaches to? Do I need to write an entire script to make that sprite change? I don't know. I'm going to put some images, don't know if they'll help, but any ideas of what to do?

#

Here's that code if you're wondering:

public class CardDisplay : MonoBehaviour
{
    public Card cardData;

    public Sprite cardSprites;
    public Sprite[] mainCardSprites;
    public Sprite[] specialCardSprites;

}
``` Thanks
timber tide
untold shore
timber tide
#

So two ways I'd tackle this. One, being the basic idea of having multiple prefabs, each using a single card sprite. Two, scriptable objects can be your plain data you reference such that you have a single card prefab that reads from these data types.

#

Your idea isn't that bad either. Is there a problem with your implementation because if it works it works ;p

hallow hound
#

omg im so annoyed, the code was working perfectly, change some positions, started giving errors, ctr z to what i changed, still same errors and now 1 hour later still DONT KNOW WHAT is giving the errors 😭

#

its says that the initialization of a class is null but i didnt changed any of that

wintry quarry
#

You need to debug your code

hallow hound
#

Yeah! i added a lot of logs, and evrything is working EXCEPT for a json wrapper, that was working fine, didnt touched and now doesnt work and dont know how to fix it

untold shore
hallow hound
#

look, the log says that the data was loaded but when i log the voxelDataArray it says null

#

but i redid the json, with only one VoxelShape with super basic data and it still says null, all this because i change a position from 1 to 0.5f, but i revert it and still giving errors

timber tide
#

If you want to bind it at runtime, you need to explicitly grab the image component via GetComponent then access the sprite property.

#

Or, if you want simplicity for now, consider the first option I mentioned and just custom make each card into its own prefab

untold shore
#

Which way would be better for the game? If its more difficult Im willing to learn.

hallow hound
teal viper
#

And I'm not sure if that json is valid. Did you serialize it in unity as well? Or type manually?

timber tide
hallow hound
#

I DONT KNOW HOW i deleted that without knowing

#

thanks so much

naive pawn
teal viper
naive pawn
#

if it was invalid the ide probably wouldve highlighted errors

late abyss
#

I have some screenshots of the game I'm still developing. Just to double check, does it look like I have defined what sounds I want to be used in both Unity and Visual Studio? I have a problem with my bird where when it hits a pipe, the game over music plays, but not when the bird goes off screen. Any suggestions?

naive pawn
#

(or it would mistake it for jsonc...)

naive pawn
late abyss
#

I can try that. I could also try to play the sound in the game over function

rocky canyon
#

be courteous to mobile users use !code to share ur code

eternal falconBOT
late abyss
untold shore
#

Quick question, what method should I use if Im trying to get a random image from this image array?

    public void Start()
    {
        cardSprites = GameObject.Find("CardDisplay").GetComponent<Image>();
        Image[] mainCardSprites = Resources.LoadAll<Image>("Cards/Main");
    
        Image[] specialCardSprites = Resources.LoadAll<Image>("Cards/Special");
    }
/// (another function)
    {

            cardSprites = /// this should be a random image from mainCardSprites;

Thanks, just really confused and having trouble finding it for images.

rocky canyon
#

its just a random number between 0 - .length right?

#

collection[Random.Range]

#
    public void AssignRandomCard()
    {
        int randomIndex = Random.Range(0, mainCardSprites.Length); 
        cardSprites.sprite = mainCardSprites[randomIndex];
}```
#

capital L i believe

untold shore
#

Thank yall so much!!!!!

#

Hey, it keeps giving me this error with that, any ideas?

#

(I'm using Spawn's, but removed .sprite since CardSprites are images)

naive pawn
#

you don't need to stringify that, Debug.Log does it for you

untold shore
#

Yeah, its something with the naming of the folders. Need to figure out how to get them in (changed it to sprites for a second to see if I could make it fix that way)

rocky canyon
#

whats something with the naming? whats happening?

rocky canyon
untold shore
#

It's the folders I guess? Here are the folders - it won't let me go into the folders to access the sprites

untold shore
rocky canyon
#

soo Sprite[] and Image[] neither one populate?

#

where do u run this code? can u share the full script? !code

eternal falconBOT
rocky canyon
#

oh true... why do u have "Main", you'll have to drop down b/c its a SubFolder

#
  • Cards
    • Main
untold shore
#

Still gives this problem for some reason? (It equals 0)
I'll get the entire script on a pastecode, its a lot

rocky canyon
#

well u can just give us the relevant parts

untold shore
#

Right, hold on rq...

    public void Awake()
    {
        cardSprites = GameObject.Find("CardDisplay").GetComponent<Image>();
        Image[] mainCardSprites = Resources.LoadAll<Image>("Cards/Main");
    
        Image[] specialCardSprites = Resources.LoadAll<Image>("Cards/Special");
    }
        public void AssignRandomCard()
    {   
        Sprite[] mainCardSprites = Resources.LoadAll<Sprite>("Cards/Main");
        Debug.Log(mainCardSprites.Length);
        Image[] specialCardSprites = Resources.LoadAll<Image>("Special");
        Debug.Log(specialCardSprites.Length);
        int randomIndex = Random.Range(0, mainCardSprites.Length); 
        cardSprites.sprite = mainCardSprites[randomIndex];
    }
#

Ooohh, so I would have to do Cards/Main/ChineseZodiacs?

#

Omg. its because I forgot to do sprites.

#

(context they were game objects and I had sprites in a different folder.)

#

Thank y'all so much for dealing with my dumb brain 😭 😂

upper prawn
#

Hi, I'm looking for advice on managing all my crop models/colliders/info for a stardew clone.
I'm thinking I would have some kind of lookup table generated from a config file, where I can associate seeds to the crop growth stages, and harvestable items, and animations.
However I don't know how to dynamically load/select the models for these things. It seems like I would use prefabs, but I'm still not sure how to handle all this dynamically. Any advice?

violet agate
#

the custom event doesnt show up in the name selector

toxic frigate
#

hello everyone, this snippet of code is attached to a cannon script i have. when the platform the cannon is on (say, a vehicle or a ship) rotates along any axis, it does not account for the root body's rotation despite my best efforts. how do i make the code use either global rotation or account for the root body's rotation? https://paste.ofcode.org/d45vNsnMHBaiG6MxQa6UBh

nova kite
#

Is there a channel that gives you a road map to how to start because every time I try and learn game development I give up in two hours, I tried everything and idk what to do

alpine fjord
eternal falconBOT
#

:teacher: Unity Learn ↗

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

nova kite
#

I wanted to make a simple game of dragging a ball and shooting it like those games where you hit blocks, just to see how that can work, I made a ball object and two walls and got stuck writing a script for the ball to draw a line in front of it when you drag the mouse

teal viper
nova kite
#

I’m more familiar with c++ since we are learning that in college and it is kind of similar but I just don’t know how to learn the libraries and functions that will help me execute these actions

#

For example the mouse detection at a certain position

#

Or dragging, or drawing lines or anything

teal viper
#

Other than that, you'll need to get used to researching and learning on your own.

#

Google should be your most used website.

nova kite
#

I tried learning with chatGPT but it just gives me the answer which doesn’t help lol

alpine fjord
#

Do NOT use chatgpt when you're learning. It's wrong just as often as it's right. And any code it gives you, is iffy.

nova kite
#

What do you search when you search for specific problems? Because it’s even version sensitive, for example I saw a video about mouse detection in Unity and it showed a line of code that starts with Mouse(being an object) but in my version I got an error because Mouse wasn’t an object

#

See I thought it’s a double because the pixels in the video had a dot too

#

And also there was a world screen function which from what I understood is the position of only the inside rendered screen and not the actual screen

#

And got completely lost haha

alpine fjord
#

I read something awhile ago, chatgpt was asked to multiply two 5 digit numbers. And it gave you the wrong answer.

nova kite
#

I’ll try and follow the general API tutorial and see if I understand

nova kite
nova kite
#

I wish I could use c++ tho I’m way more comfortable with that haha, is there a script by any chance that allows you to do that with Unity

#

Welp I’ll just learn c# then haha

#

At least no pointers

#

Is that a game engine?

#

Oh lol

#

I tried unreal but I don’t like the interface and creating a 2D game on it is weird

#

And not many tutorials because everyone are using the other option that’s like a coding blocks thingy

#

Thank you! I’ll take a look at the beginner tutorial first so I don’t bother you with questions that I can get the answers to there!😅

alpine fjord
#

Google is your friend.

nova kite
#

It feels too broad searching a specific problem on google🥲

#

I’ll follow the basics for now tho, get familiar with the interface

#

Thank you guys, this motivated me again haha

alpine fjord
nova kite
#

Yes I just need to understand how to apply an answer that I see on google to my problem🥲

#

Because usually it involves some level of pre understanding the problem

teal viper
nova kite
#

So you can infer what you need to take from it

nova kite
teal viper
nova kite
#

Because that feels like not learning if so

teal viper
rocky canyon
#

u specify ur final search to ur problem by debugging the bigger problem into smaller more specific problems..
the ones with simple answers a dime-a-dozen on search engines

teal viper
nova kite
#

I see, and then how do you remember the exact function that helped solve the problem in that case or the exact line of code

rocky canyon
#

u remember out of habit

nova kite
#

Yea the most I’ve done with code so far is some basic data structures😅

teal viper
#

Imagine you're building a rocket and you don't know anything about rocket engines or the chemistry of it's fuel. You're not gonna build the rocket until you learn these more basic concepts/building blocks.

nova kite
#

Oh I’ve done classes and objects and polymorphism

#

I just never had the opportunity to apply it to anything

rocky canyon
#

coolio.. u'd have opportunities in unity

nova kite
#

That’s what I’m looking forward to😄

toxic frigate
#

i did some more tinkering and used Vector3.ProjectOnPlane but it didnt do anything

teal viper
toxic frigate
#

i have some ships firing at each other, this is when the ship's tilt is negligible, and its splashing roughly around the target

#

and when its tilted like this it ignores the root rotation and splashes into the water

and conversely when its tilted the other way it overshoots

#

this is the best way i can visualize it at the moment i would record a video im not at my main computer at the moment

teal viper
toxic frigate
#

yes

#

yes

#

how would i convert it to world space?

#

yes

#

this is the whole hierarchy

#

yes

acoustic sequoia
#

Hey does anyone know how to pass in a transform into the inspector of a unityevent?
ive tried this:
public UnityEvent<Transform> onSelect, onDeselect, onClick;
invoking like this:

  {
    onSelect.Invoke(transform);
  }```

hmm. neverming, there was just a unity editor display problem. fixed it by reopening my proj
elfin sigil
#

Hi! Im a little stuck trying to alter this code. Currently, it shoots a projectile in the direction the player is moving. I'm wanting to set it to shoot it in the direction the mouse is in? Thanks

 ```   private void ThrowProjectile(int projectileIndex)
    {
        GameObject projectileInstance = m_projectilePool.GetAvailableInstance();
        projectileInstance.transform.position = m_projectileSpawnPoint.position;
        projectileInstance.SetActive(true);
        Projectile projectile = projectileInstance.GetComponent<Projectile>();

        Vector2 baseDirection = m_character.FacingDirection; // Get the character's current facing direction.

        float angleOffset = (m_sheet.spread / m_sheet.projectileCount) * projectileIndex - (m_sheet.spread / 2.0f);

        // Rotate the direction by the spread angle.
        Vector2 direction = Quaternion.Euler(0, 0, angleOffset) * baseDirection;

        projectile.Throw(DamageSolver.SolveDamageOutput(m_character, m_sheet.damageDescriptor), direction, m_sheet.projectileSpeed);
    }
}

}

astral falcon
visual linden
slender nymph
elfin sigil
#

Sorry I should have clarified, this is 2D. I tried experimenting with ScreenToWorldPoint but wasn't having much luck

slender nymph
#

Show what you tried with it

visual linden
elfin sigil
#

I didn't save it unfortunately but I'll look into it and give it another shot. Very new to this, thanks

elfin sigil
slender nymph
#

Note that it will likely be easier and make more sense for you to use Debug.DrawLine instead

elfin sigil
#
        {
            GameObject projectileInstance = m_projectilePool.GetAvailableInstance();
            projectileInstance.transform.position = m_projectileSpawnPoint.position;
            projectileInstance.SetActive(true);
            Projectile projectile = projectileInstance.GetComponent<Projectile>();
            
            Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mouseWorldPosition.z = 0; 

            Vector2 directionToMouse = (mouseWorldPosition - m_projectileSpawnPoint.position).normalized;

            float angleOffset = (m_sheet.spread / m_sheet.projectileCount) * projectileIndex - (m_sheet.spread / 2.0f);

            Vector2 direction = Quaternion.Euler(0, 0, angleOffset) * directionToMouse;

            projectile.Throw(DamageSolver.SolveDamageOutput(m_character, m_sheet.damageDescriptor), direction, m_sheet.projectileSpeed);
        }``` 
This crashes the game when I use the ability
astral falcon
elfin sigil
#

No, just the game view

astral falcon
#

Gameview you mean build runtime?

#

I am not aware of a crash only crashing a view 😉 do you get any logs?

elfin sigil
#

No, just in the editor view

visual linden
#

What does your Throw method in Projectile look like? I don't see how the rest of the code would cause a crash.

elfin sigil
#

There's no other reference to the mouse in the project fyi

#

if that could be an issue

slender nymph
elfin sigil
#

The rest of the code: ``` public class ProjectileAbility : ActiveAbility<ProjectileAbilitySheet>
{
[Header("References")]
[SerializeField] private Animator m_animator = null;
[SerializeField] private InstancePool m_projectilePool = null;
[SerializeField] private Transform m_projectileSpawnPoint = null;

    [Header("Animation Parameters")]
    [SerializeField] private string m_fireAnimationParameter = "fire";

    public override void Init(CharacterBase character, AbilitySheet settings)
    {
        base.Init(character, settings);

        Debug.Assert(m_animator, ErrorMessages.InspectorMissingComponentReference<Animator>());
        Debug.Assert(m_animator.GetBehaviour<StateMessageDispatcher>(), string.Format("{0} not found on the projectile animator controller", typeof(StateMessageDispatcher).Name));
    }

    protected override void Fire()
    {
        m_animator?.SetTrigger(m_fireAnimationParameter);
    }

    public void OnChargeAnimationEnd()
    {
        if (!m_character.dead)
        {
            for (int i = 0; i < m_sheet.projectileCount; ++i)
            {
                ThrowProjectile(i);
            }

            TerminateCasting();
        }
    }```
#

Wait sorry, its pausing the game. The projectile fires but it stays on the character, and they can no longer move.

astral falcon
#

Any error in the logs?

#

and ++i should be i++, right?

slender nymph
#

Yeah sounds like an exception with error pause enabled

visual linden
slender nymph
elfin sigil
#

Nothing in logs. Thanks for the tip 🙂

astral falcon
void thicket
astral falcon
slender nymph
visual linden
void thicket
#

ThrowProjectile(++i) and ThrowProjectile(i++) would be different

astral falcon
#

The more you know 🙂

elfin sigil
#

🤦‍♂️

#

I now know how to use the console

#
UnityEngine.Input.get_mousePosition () (at <c8b1b15e0c1a4cccb2a9ed91e2ed21c8>:0)```
astral falcon
#

So you need to use the new input system to get your mouse position 🙂

void thicket
#

Oh yeah, idk why it has to block the legacy one, but there is also option to use both iirc

visual linden
#

Alternatively, you can switch to "Both" in Player Settings. But I would also suggest learning the New Input System.

astral falcon
#

Yes, please step away from that very old one. once you get the grasp on the new input system, its so comfortable to use and play around with

visual linden
#

A lot of tutorials and courses use the legacy input system though, so if you're trying to follow along with something, it might be worth simply setting your project to "Both" so you're not blocked in your current learning journey.

ebon crow
#

Hi everyone

burnt vapor
# ebon crow Hi everyone

Hi there, if you have a question about your code then please share here and don't forget to share the actual code

tired hull
#

Hi im new to unity and im trying to add boundarys to my space shooter game but i get these errors in the console, is there anything in my script for boundarys i should change to fix this?.

gaunt cipher
teal viper
#

Also,configure your !ide, as you wouldn't be able to get help here otherwise.

eternal falconBOT
tired hull
burnt vapor
teal viper
#

I don't see how that's related to scopes. Variable declaration maybe

fierce lynx
#

Do y’all allow talking about C++ here? I’ve seen some post online where people talk about cpp in unity communities such as in Reddit.

fierce lynx
#

ok

teal viper
grand snow
#

you can use native code in unity if its built into an dll/so/dylib (or if the source code is included for ios/android)

visual linden
teal viper
wintry kiln
#

hello im trying to develop a 2d platformer game and ive been struggling with the changing of the scenes when i go through a door. im not sure on what type of scripts i have to use: i tried with a script for the door but i cant seem to be able to choose the position on where the player ge transported so idk what to do now. if anyone knows how to resolve this please text me

finite dove
wintry kiln
#

im trying to write a script that i can attach to the doors and can "transport" the player from 1 scene to the other. im gonna try to use the scriptable object and see how it goes

dark laurel
wintry kiln
#

ohhh thank you so much

#

im gonna try it right now

snow warren
#

Ok i am having a server problem here

#

i wonder if there is an easy fix for this

#

I am using Playfab and in playfab there is no way for finding out if your friend is currently online or offline so i wrote a script that updates the friends data on server and add to it 1 minutes ahead of its timezone
if someone in the same time zone is friends with this guy he will get the timer 1 minute ahead always from his time zone

now when the player is offline the 1 minute ahead wont be updated and seeing this if time > server.aheadtime then the game would know that the friend is offline

#

but for someone who isnt in the same time zone this cheap fix wont work

#

is there a way to use a universal time

#

or something similar

languid spire
#

we are not here to provide support for 3rd party assets

snow warren
languid spire
snow warren
grand snow
snow warren
#

no matter the culture info
if i change the culture code to "us" then i will get us time zone

#

i can then process requests based on that time only

grand snow
#

you want to avoid timezones with time calculations

languid spire
#

that wont work

snow warren
#

any other options?

languid spire
#

yes use UTC Date/Time

grand snow
#

DateTime.UtcNow is your friend 🙂

snow warren
#

any examples on how it is implemented?

snow warren
#

wait time zones are utc + something

#

so with utc you only get the utc time

#

no additions to it with respect to region

languid spire
#

and you can convert UTC time to Local Time using the DateTime class

dark laurel
# snow warren no additions to it with respect to region

(this username is super annoying because you can't be @'d easily FYI)

Whenever you deal with dates, the time zone of the date is irrelevant - you should always be handling it (or thinking of it) as a UTC based date - if you try to get into the business of doing time zone stuff, you're gonna mess up, trust me. It's way more complex than you think.

If you need to make a date, use DateTime.UtcNow (not DateTime.Now!) and increment/decrement it with timespans using the overloaded operators (sounds complex, looks simple):

DateTime oneMinuteFromNow = DateTime.UtcNow + TimeSpan.FromMinutes(1);
#

whenever you render the datetime and need to show it to a user in local time, then you'll display it using the culture info, but for things under the hood, you should always treat dates as UTC based so you dont get into the bugs of time zone stuff

snow warren
#

i am gonna use it right away and see if it works

dark laurel
#

maybe change your username or display name to Code Red while you're at it? 😉

snow warren
#

why?

#

Here changed it for this server only
good luck

dark laurel
#

so I can type @snow warren instead of scrolling up to find a message of yours and hitting reply 🙂 (also that ascii typeface is awful and hard to read sorry notsorry)

snow warren
#

just slide and reply

snow warren
#

ascii uses 4 bytes for one character

#

whereas in C++ by default its utf which stores a character as one whole byte

#

C# by default uses 4 bytes as one character so ascii by default

#

am i right or wrong?

grand snow
#

er wat

#

c# uses utf8 for strings always and its variable in length what a char is

snow warren
#

*utc *utf

#

type mistake

snow warren
#

sorry forgot 2 bytes

#

man i gotta wash my brain

elfin knot
#

starting a 2d project for the first time in unity
what's a good pattern for organizing different screens/views ?
for example overworld and combat views ?

languid spire
snow warren
dark laurel
teal viper
gentle bone
#

google knows better

dark laurel
#

@elfin knot (additive and async scene loading aren't really a problem as you get started)

elfin knot
snow warren
#

how??

dark laurel
#

As far as screens/views, I'd say the same. When a rendering class is too big (your opinion on "big") then break it apart.

elfin knot
#

ok, i'll start with overworld and by the time i get to other screens it will probably be more apparent

dark laurel
#

Make sure you distinguish Scene and "screen" - a scene is a unity "box" where all the game objects exist. A "screen" is a UI idea that you might create with a single game object (or script) or dozens

elfin knot
#

like i have game objects and game board
but also things like esc menu

#

in 3d i'd use ui toolkit for esc menu
but since it's 2d i'm not sure how people usually go about this

snow warren
#

tho you can use third party UI library by their C# bindings like Imgui etc

#

depends on what you prefer

dark laurel
dark laurel
#

I do all my stuff with unity UI

languid spire
dark laurel
#

(IMGUI is kind of weird)

#

I'd suggest UnityUI if you're just interested in things like huds or 2d based ui games

elfin knot
#

just in general, not a specific library, just to understand if it's more common to use 2d game objects to make UIs in 2d
or use specialized UI libraries

dark laurel
#

it depends on what you're trying to do 🙂

#

UIToolkit is like steve said - html-ish? xml-ish? based on flexbox model - it's like.. great for quickly laying out input boxes, forms, etc.. maybe more for data applications over games

#

uGUI (aka "unity ui") is like.. draw to a canvas, put this image at 100, 100, have this button send some event back to the code

elfin knot
#

for game board and game pieces i will use 2d game objects
but for things like hud and esc menu, main menu and so on i'm not so sure

burnt vapor
# snow warren how??

Different formats allow for more characters and therefore also things like emojis and such. Compared to ASCII which is strictly letters and numbers and a few other symbols

dark laurel
#

IMGUI is more for like programmers and people doing things in the editor (like assets)

languid spire
dark laurel
elfin knot
snow warren
#

UGUI or Unity UI is much better when it comes to UI development
more control and animation controls and many other stuff plus you can control UI behaviours with C# scripts as well like loading screens logins and many other stuff

elfin knot
#

this really helps

polar kraken
#

Hey all,
I want to prevent character to enter water area. What is the best way to do that ?

languid spire
swift crag
polar kraken
swift crag
#

Do you have water surrounding the entire play area, or is this more of a lake?

languid spire
polar kraken
#

More lake and rivers. And it is 3D

swift crag
polar kraken
polar kraken
swift crag
#

okay, and the player isn't going to be flying high over the water?

#

it should just be an impassable barrier

polar kraken
#

Also I've tried to use raycasting and find out if the character is near water. I can figure that out but the issue is, it got time consuming to prevent player stop before that. Also I'm not sure how does it look like when other conditions happen. Like in strafe mode or when jumping.

polar kraken
swift crag
#

You could draw a path around the water and then create box colliders along it. That'd be pretty easy to do with an editor script and the Splines package.

polar kraken
#

For instance, I made this one by probuilder. But still I'm not sure if it is a good approach or it might be heavy because it is complex mesh collider.

swift crag
#

I don't know too much about mesh collider performance

polar kraken
wintry quarry
#

Put a bunch of box colliders down by hand around the perimeter 👅

languid spire
polar acorn
#

If these are static bodies of water and aren't procedurally generated or anything then placing colliders by hand is 100% the best course of action.

Sometimes, tedious data entry is just part of the job. Unless you've got a ludicrous amount of water, programmatically doing it is likely to take longer and not really be very generalizeable.

swift crag
#

I'd try to outline it and then generate the collider from that outline, at least.

stuck palm
#
void OnDisable() {
    if (renderers == null) {
      renderers = GetComponentsInChildren<Renderer>();
    }

    foreach (var rdr in renderers) {
      var materials = rdr.materials.ToList();

      if (materials.Contains(outlineMaskMaterial)) {
        materials.Remove(outlineMaskMaterial);
      }
      if (materials.Contains(outlineFillMaterial)) {
        materials.Remove(outlineFillMaterial);
      }

      rdr.materials = materials.ToArray();
    }
  }

I have this code thats meant to remove materials from a scene. However it is not doing this, why is that? There are no errors, and the values are all set. No idea whats happening here

swift crag
#

materials contains instanced materials

#

they're copies of the originals

stuck palm
#

wait a sec

#

the outline has (instance) (instance) lmao

#

wtf

swift crag
#

If you assign that into material or materials, it gets instantiated again

long jacinth
swift crag
#

You can use sharedMaterial and sharedMaterials to avoid instantiation

#

Of course, you'll then have to make sure you aren't modifying a material that's shared by many renderers

stuck palm
#

I don't understand the reference that the script has then. it's not in the renderer list, so where is it even being used?

swift crag
stuck palm
#

no, OutlineMask is the one inside resources

grand junco
#

Hi everyone! Looks like Im struggling with pretty default issue so I will be glad to hear any advices on how to resolve it.
I have 5 cubes of the same size and with same Y coordinate and use them as floor floor. Also I have cube which should slide on them some distance after rb.AddForce(force, ForceMode.VelocityChange.) called in my code. It slides as expected until it reach border between two of floor object - then it stops(red line logs on screenshot shows what force my code tries to apply each fixed update). My only idea how to resolve it - is add some forces in up direction to help rigidbody moving on seams but it looks bad

swift crag
stuck palm
#

why is the render list not something you can modify directly btw?

swift crag
#

"Render list"?

stuck palm
#

like you have to make a copy and and then assign that copy back

stuck palm
swift crag
#

Because Unity isn't actually using an array of Material objects internally

#

it's something off in native code land

#

materials is a property that creates an array of Material objects

#

(or uses an array to reconfigure the renderer)

long jacinth
lapis parrot
#

why when i try to add text it doesnt work?

grand snow
burnt vapor
eternal falconBOT
lapis parrot
burnt vapor
#

Gonna need some more context if you want help. Code, maybe screenshots

fringe plover
long jacinth
#

ok

grand junco
swift crag
opaque owl
#

does anyone have any idea what could be causing this please 😭 this is killing my hobby project
-# unity 6000.0.19f1

verbal dome
#

That's the first thing I do when unity starts to hang

#

Although it hasnt really happened since I moved to LTS

swift crag
#

yes -- mangled asset data can cause very weird behaviors

#

the Library contains data generated from your assets, as well as stuff like compiled shader variants

#

The editor will forget which scene you had open, so it'll open into a blank scene

opaque owl
#

thanks ill try that, for the record im upgrading to 6000.0.31f1

swift crag
#

This is similar to running Assets > Reimport All, although that doesn't forget things like the currently open scene

severe onyx
#

how would I go about moving an object across the screen in a wave pattern ie a constantly changing direction vector

swift crag
#

there are two main ways you'd do this

#

the first is "iterative": you add a small amount to the current position every frame

swift crag
#

consider something like this

Vector3 vec = Vector3.right;
float angle = Mathf.Sin(Time.time) * 45;
vec = Quaternion.AngleAxis(angle, Vector3.forward) * vec;
transform.position += vec * Time.deltaTime;

This would steer back and forth across a 90 degree range

#

The other approach would be to just directly calculate a position

#
Vector3 pos = default;
pos.y = Time.time;
pos.x = Mathf.Sin(Time.time);
transform.position = pos;
severe onyx
#

yeah I was imagining something like the latter. using a sine was what I expected but I kinda blanked on how to calculate it over time. using Time.time seems very obvious in hindsight, duh

#

works like a charm, can scale it with a speed variable and add it as an offset if the starting position is non-zero, perfect

#

should I be worried about performance if there's a lot of entities on screen using that function?

verbal dome
#

I don't think there's a more performant way to do it, at least with gameobject workflow

#

From the two approaches Fen provided I'd assume that the second one is cheaper

long jacinth
#

at least for why its not upgrading part

#
            {   
                if(hovering != null && instantiatedButton != null)
                {
                    hovering = instantiatedButton.GetComponent<HoverCheck>().Hovering;
                }

                if (instantiatedButton != null && hovering) 
                { 
                    if (building.GetComponent<BuildingStats>().level < 0) 
                    {   
                        gameObject.GetComponent<Image>().color = instantiatedButton.GetComponent<ColorContainer>().BuildingButtonColor;
                    }   
                    else 
                    {   
                        gameObject.GetComponent<Image>().color = instantiatedButton.GetComponent<ColorContainer>().EmptyButtonColor;
                
                    }
                }
            }```