#archived-code-general

1 messages · Page 92 of 1

ruby fulcrum
#

so even if you reset y velocity in the air

#

your object will still fall

spark plover
#

Hi everyone,
I'm trying to setup my Unity project. I'm using VS code as external tools. My project has a multi-root setup. I saved a [project-name].code-workspace in the root directory of the project path. Now in the editor external tools arguments, I'm using "$(ProjectPath)/[project-name].code-workspace" -g "$(File)":$(Line):$(Column).
This works as expected when opening the project from unity : workspace is loaded, file script and line number are opening as well as it should.
Still this arguments in the external tools editor window is common for all the Unity project which use the same editor version, so it is fine only if I'm working on the correct project.
Do you know if there is an argument (like the $ProjectPath) which defines the project name ? Or anything like this I could use ?

gray mural
#
Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported since Unity 5.

does anyone know how to use MeshCollider with kinematic Rigidbody (because I AddForce to it) ?

hexed pecan
#

If its not accurate enough to your shape, you can use multiple convex colliders, or preferably multiple primitive colliders (box, sphere, capsule) to approximate the shape

gray mural
hexed pecan
#

If its still unclear, google convex vs. concave

cobalt wave
#
if(rb.velocity.x > maxspeed
{
  float clampedx = Mathf.Clamp(rb.velocity.x, maxspeed);
  rb.velocity = new Vector2(clampedx, rb.velocity.y);
}

sorry if it has already been solved

#

oh it has been solved more elegantly, nice

stoic flame
#

I'm trying to make the code generates only 2 obstacles, why is it generate 3??

ashen yoke
#

probably because you have 3 children

#

or maybe its more convoluted

stoic flame
stoic flame
ashen yoke
#

you just confirmed that you have 3 spawners

dusk apex
stoic flame
#

I want it to generate only maximum of 2

#

And left one of them empty

dusk apex
#

Why not just generate two.. at specific locations?

#

Or set one inactive randomly

stoic flame
stoic flame
warm night
#

Hey, I have an inventory which has slots, and i have a hotbar (which is a different gameobject) which has 5 slots. I want to do a drag & drop system, like dragging an item frm the inventory to the hotbar. I tried to use the interfaces for that, but in my hotbar, i have the interface "IDropHandler", so the method OnDrop as well, but the variable "pointerEventData.pointerDrag" returns me the slot on the inventory where the item was before dragging... someone has an idea for that?

#

I just missed an information, it should fix the pb, thanks anyway ^^'

hard estuary
#

Oh wait, I think I misunderstood the scenario. 🤔

stoic flame
#

oh

hard estuary
#

Well, when I'm looking at this code, it shouldn't spawn more than 2 objects, unless there are several instances of this script on the scene.

manic gulch
#

This is an Editor question;

#

How do I detect if there is mouse input in a specific Editor Window? For instance the Timeline editor window

hexed pecan
manic gulch
#

oh my bad

fresh forum
#

I've got a ball that follows the mouse on every Update().

        debugBallPos = debugBall.position;
        debugBall.position = Vector3.Lerp(debugBallPos, mousePos, 0.1f);

debugBallPos is a vector 2 version of the debugBall's position.
Line 2 just lerps it to the position of the mouse.

My question is, how do I constrain it to not go farther than a limit from the skeleton's torso

dusk apex
#

Acquire the distance between mouse and skeleton and set the target constraint of Lerp to skeleton position + mouse direction * Mathf.Min(distance, max).
Note: this would produce a circular max distance constraint.

digital lava
#

how do i fix this

fresh forum
simple egret
dusk apex
fresh forum
digital lava
#

ok it fixed it but now i got another error

simple egret
#

Configure your code editor

#

It's required to get help here

digital lava
#

i dont know how i pressed the link you sent

dusk apex
simple egret
#

You read the page that opens and apply the steps in it

digital lava
#

im blind or someting beacuse i cant find any windows < package manager

simple egret
#

You're blind

#

It's in Unity

digital lava
fresh forum
digital lava
dusk apex
fresh forum
#

but why mouse and ball?

digital lava
fresh forum
#

the ball is alr getting lerped to the mouse

digital lava
#

can you help now?

simple egret
digital lava
simple egret
#

Yeah, it's still not set up properly

digital lava
#

wait i can show i got everyting

simple egret
#

If you haven't done that already, restart it

digital lava
#

alr

simple egret
#

Also the guide isn't just about updating everything, there are more steps, go through it all

digital lava
#

ok

#

im new sry btw if im not so good

dusk apex
digital lava
#

what now

fresh forum
simple egret
#

Your errors will be underlined red in the code

digital lava
#

it aint any text thats red underlined tho

simple egret
#

If that's not the case, then pick up the guide where you left off and finish it

digital lava
simple egret
#

Well you should be able to determine that yourself, since you have control on what you install on your computer
But yes, that's the right thing to select

digital lava
#

ok

#

the error is still there

#

idk what the problem is

simple egret
#

Yes that won't solve your error

digital lava
#

then what will

simple egret
#

It's meant to give you a better programming experience

digital lava
#

wait

#

it is a red underline now

#

i fixed it

#

letss gooooooo

simple egret
#

See? The underline did it all, I didn't even need to tell you where the error was or what to do

rotund burrow
#

How do I make this visible in the inspector

simple egret
#

You can't, the setter must not be private or protected

rotund burrow
#

found the solution - field: SerializeField

lucid valley
#

^ yup, need to specify the backing field of the auto property in order to serialise it

simple egret
#

The attribute not erroring when put on a property is plain stupid

#

Ah, Unity, Peak development experience

dusk apex
#

Pretty much. Unity needs to suggest the field variant

fresh forum
#

is this it?

dusk apex
#

Mouse direction

fresh forum
#

?

dusk apex
#

direction would be equaled to mouse position minus skeleton position (screen space), normalized

fresh forum
#

aha

simple egret
fresh forum
#

?

ashen yoke
dusk apex
#
var distance = ...
var direction = ...
debugBall.position = Vector3.MoveTowards(debugBall.position, debugBall.position + direction * Mathf.Min(distance, max), speed);```something of the sort.. (coded from mobile discord - possible errors)
fresh forum
#
 debugBall.position = Vector3.Lerp(debugBallPos, torso.position + (mousePos - torso.position).normalized * Mathf.Min(Vector3.Distance(torso.position, mousePos), flingLimit), 0.1f);```
#

this is what I have

#

Its close

#

but it doesn't limit the distance

#

it just reduces it

dusk apex
#

Lerp's probably not what you'd want to use

fresh forum
#

move towards?

dusk apex
#

Aye

fresh forum
#

Max dist delta?

#

what value would be good?

dusk apex
#

That's just how fast you'd want the ball to go towards your mouse - maximum speed

#

Try some values

fresh forum
#

Very similar results

#

I have 3 monitors

dusk apex
#

How are you acquiring mouse position?

fresh forum
#

it doesnt hard limit the circle

fresh forum
dusk apex
#

Show what you've got.

fresh forum
#

then I convert it to world position

dusk apex
#

That would be screen space. Alright

fresh forum
#
        mousePos = Input.mousePosition;
        mousePos.z = 10;
        mousePos = Camera.main.ScreenToWorldPoint(mousePos);
dusk apex
#

Set z to zero, is the usual pattern

#

It's -10 by default

fresh forum
#

yea

dusk apex
#

Unless your project orientation is different

#

Show your current implementation

fresh forum
#

Of?

#

the character controller?

dusk apex
#

The assignment of position and whatnot

#

Assuming you're not using lerp anymore

fresh forum
#

yes

#

im not

dusk apex
#

Set the z position after converting to world space

fresh forum
#

to?

#

0?

dusk apex
#

It's already zero in screen space

#

Yes

fresh forum
#

Now it just follows the mouse

#

spot on

#
        mousePos = Input.mousePosition;
        mousePos = Camera.main.ScreenToWorldPoint(mousePos);
        mousePos.z = 0;
dusk apex
#

Congratulations

fresh forum
#

but it still doesnt limit the ball

#

:p

dusk apex
#

What is fling limit?

fresh forum
#

Its meant to be the distance

#

but I havent implemented it

#

into anything yet

#

which i probably should lol

dusk apex
#

That would be the maximum distance the ball would be from the skeleton

fresh forum
#

yes

dusk apex
#

Everything else was for moving the ball towards the mouse. Seems like you've got it, good job.

fresh forum
#

?

#

OH

#

You;re right lol

#

thxx

fresh forum
#

lemme try send a clip

#

This happens even though the Fling values are normal

#

fling Velocity

shrewd meteor
#

why am I getting this error in a completely new unity scene? I've not added anything and yet I get this error? I'm using unity 2021.3.24

lean sail
#

Version control package, update or remove it. Theres a bug with it

#

Lots of people had that issue

shrewd meteor
#

uuuh, sorry if I'm not understandingt correctly, update what exactly? Should I not use this unity version?

lean sail
#

The package for version control is currently bugged. Your unity version is fine

#

Search for version control in your package manager

shrewd meteor
young wigeon
#

I have an attack (the big white rectangle) which is instantiated when the player attacks and then deleted a bit later
and I want it to do stuff when colliding with objects with the tags "enemy" or "bouncable"
but it's not working?

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("attack collided with " + collision.gameObject.name);

        if (collision.gameObject.tag == "enemy" || collision.gameObject.tag == "bouncable")
        {
            Debug.Log("bounce");
        }
    }

neither of the debug logs are triggering
the script is on the gameobject of the attack

lean sail
#

Oops that's 3d, updated link

young wigeon
#

the attack should be triggered by the object right?

tropic quartz
#

No rigidbody?

young wigeon
#

it needs a rigidbody? 💀
i thought it just needed a collider

tropic quartz
#

Yup. Or at least the 3D one does.

ancient sail
#

Hey everyone, how do I make raycast2d stop from giving me a bunch of errors when it hits nothing

tropic quartz
tropic quartz
#

That way it won't do anything when it hits nothingness (returns null)

soft shard
cobalt wave
fresh forum
cobalt wave
#

move the rb.velocity stuff in FixedUpdate() and change Time.deltaTime to Time.fixedDeltaTime

fresh forum
#

but I think I've already found a fix

cobalt wave
#

you probably haven't

#

:/

fresh forum
#

maybe

cobalt wave
cobalt wave
#

Input still should be in Update

fresh forum
#

gocha

#

thx

cobalt wave
#

use a container value to check when you press a button in update
check that container value in the if statement and reset it back to false at the end of the fixed update

#
bool mousePress = false;
void Update()
{
...
  mousePress = mousePress || Input.GetMouseDown(0); //fix by @Sidia
}

void FixedUpdate()
{
...
  if(mousePress && !onCD)
    //change velocity
...
mousePress = false;
}
#

also why not just use rb.AddForce(force, ForceMode.Impulse)?

fresh forum
cobalt wave
#

well now you do :)

dusky lake
fresh forum
#

thx

cobalt wave
#

read the code again

dusky lake
#

2nd Update will set mouseDown to false before fixedupdate

cobalt wave
#

or do you mean that only the last Update will work?

dull yarrow
#

Is possible to create a class that have another class in it?
For exemple i have a item class that have (name, image, etc)
And i want to create another class, for exemple weapon, that is inside of item class or that have the the item class atributes

dusky lake
#

Use mouseDown = mouseDown || Input.GetMouseDown() then it wont reset

cobalt wave
#

yea that's a good fix

cobalt wave
dusky lake
#

Not if you set it to false in FixedUpdate

cobalt wave
#

true true

fresh forum
#

@dusky lake is correct

#

It misses a lot of inputs

cobalt wave
#

try it

dusky lake
#

Try my fix above

#

The problem is especially happening if you have a very high frame rate

cobalt wave
#

yes true

hexed pecan
#

Or just do it in Update

#

Adding a single impulse force in update is fine

#

It will take place when the next FixedUpdate/physics step happens

#

Continuous forces though, those you need to do in FixedUpdate

cobalt wave
#

just make sure to use Time.fixedDeltaTime

#

or else you'll have way too different forces applied every time

lethal plank
#

damn those lines too stupid so unity refuse to run it xd

#

unity editor when press play will not responsible xd

#

any better idea guys?

soft shard
# dull yarrow Is possible to create a class that have another class in it? For exemple i have...

It is possible, though for the case you described, I think it would be better to treat your item class as just data, in a serialized class, then create an instance of it in your weapons, armor, potions, etc classes, either as a public or [SerializeField] to set it through the inspector (serialized field is a more cleaner approach), since it sounds like your weapons etc will want to use or depend on data set from your item, another approach could be inheriting from your item class (or using interfaces), if every item like weapons, potions etc may share functionality too

leaden ice
#

your condition is checking j < something but the incrementor is incrementing a different variable called i

#

i is not j

lethal plank
#

im baka

#

second time i did it

leaden ice
#

It's an understandable and common mistake to make, 😉

lethal plank
#

XD

fresh forum
#

.velocity and AddForce as an impulse shouldn’t be affected by fps

#

My problem was fixed by removing deltatime

lethal plank
#

oh damn crashed

potent sleet
lethal plank
#

still it but j++

#

lemme try again

potent sleet
#

you put j++ on line 127 ?

lethal plank
#

yes

lethal plank
knotty cargo
#

Thank you! This is always a concept I've been scared to try, but music is my favorite part of most games, so I'm super stoked to actually face the challenge haha

dull yarrow
#

I am having a problem:
I have a item class and a Equipment class that have the item class as inheritance
In my Gameobject i have a item reference that i can place my equipment item
And i want to use for exemple a function that uses the Equipment item -> useItem(Item item)
The problem here is that i cannot use the Equipment class features
How do i turn around on this?
I cannot create a Equipment reference on my game object because other types of items will be in that reference too

vestal hornet
#

why am i getting a error here?

#

i know i have to define it in a certain way, however i cant find any information about it

#

I saw this post, but I believe they changed it because it isnt working for me

golden vessel
#

Can I assign a method to a unity event in script?

golden vessel
knotty sun
#

you cannot remove listeners assigned in the editor

golden vessel
knotty sun
wide fiber
#
public class P_Controller : MonoBehaviour
{
    [SerializeField] private InputAction Boost;
 
    private void Awake()
    {
        Boost = new InputAction("Boost", InputActionType.Button);
        Boost.AddBinding("<Keyboard>/a");
    }
   
    public InputAction GetBoost()
    {
        return Boost;
    }
}```

```cs
public class P_Movement : MonoBehaviour
{
    [SerializeField] float RotSpeed;
    [SerializeField] float RotBoost;
    float OGspeed;
    P_Controller controller;

    private void Awake()
    {
        controller = GetComponent<P_Controller>();
    }

    void Start()
    {
        OGspeed = RotSpeed;
    }

    void Update()
    {
        Boosting();
    }
    
    void Boosting()
    {
        if (controller.GetBoost().ReadValue<float>() > 0)
        {
            OGspeed = RotBoost;
            Debug.Log("bossted");
        }
        else
        {
            OGspeed = RotSpeed;
        }
    }
}

Hi sorry, why didnt this work? 😦

#

when i Press A, nothing happen?

ashen yoke
#

if properties are just methods why cant you

int prop {get;set;}
void Foo()
{
    prop;
}
somber nacelle
#

don't forget to enable your input action after creating it

wide terrace
ashen yoke
#

asking for invokation

winged mortar
ashen yoke
#

so assume there is a lazily initialized property, you cant just invoke it to force init

#

and if you do cs var a = prop;

winged mortar
#

As soon as you add () it becomes an invocation, which you can only do on functions or variables of type func or action

ashen yoke
#

there is no guarantee it wont be stripped by compiler

wide terrace
#

ah I see

winged mortar
#

Then what's the point of it being lazy?

#

If you need it preloaded anyway

ashen yoke
#

its complicated

winged mortar
#

I'm sure it is

#

Might be worth moving it over to a class and controlling it's initialization with an initialize function

#

(e.g. start a task in the constructor and then whenever you need that instance check if the task is completed)

#

But generally if you are doing these weird thjngs than that should be a trigger that your architecture doesn't support the flow that you want

ashen yoke
#

ok

ashen yoke
#

whats the proper way to lock transformations in editor apart from ExecuteAlways/Update

cobalt kraken
#

I'm trying to implement a system where when you open a door, you roll a dice and that determines what "room" is spawned. But for some reason, when I instantiate the room, the first one places PERFECTLY, but afterwards they all spawn on top of each other regardless of my offset method. I have a feeling it has something to do with the Room Properties Scriptable Object but I'm not quite sure

https://paste.ofcode.org/bWBw7H85JpLhpEHyQEv96S

#

If someone could give a quick peek it would be much appreciated!

cobalt kraken
#

ah, I got it now, thank you!

woeful slate
#

How do 2D Top down isometric games allow players to interact with the tilegrid in a systemic way? For example if I have a tree, I want my character to be able to cut it

potent sleet
#

or make the tile a scriptable tile

woeful slate
#

Would I make every interactable tile a game object?

#

And would that still work in a tilemap? Also how does layers work in this case, what if my sword chops down foliage, but my shovel digs a hole

rare nymph
#

hi, I'm trying to make a string that gives me the name of the current animation of the player in a game, this is what I have:

string currentAnimation()
{
string anim;
anim = gameObject.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).shortNameHash.ToString();
return anim;
}

But I'm getting this: error CS1503: Argument 1: cannot convert from 'method group' to 'object'

ashen yoke
potent sleet
#

this ain't it

rare nymph
#

ok I found it, I didn't put () when I called the function using Debug.Log

#

shouldn't I get the names of the animations instead of numbers?

#

like these names

somber nacelle
#

you're getting the hash of the name not the actual name

rare nymph
#

is it possible to turn it into the name?

ashen yoke
#

theres a method that converts hash to nae

somber nacelle
#

Is there? i know there's StringToHash but I don't see a method for the reverse

potent sleet
#

not sure you even can

somber nacelle
ashen yoke
#

pulled straight out of my bottom

potent sleet
#

lol

rare nymph
#

i'll try using the number

somber nacelle
#

that doesn't answer the question i asked

potent sleet
#

GetCurrentAnimatorStateInfo(0).IsName can be used to check if it's in a certain state name but that's about it

ashen yoke
#

if only hashtables existed

potent sleet
#

if you need to do things based on state just use the FSM scripting in animator

ashen yoke
#

imagine the magic of having couple kbs more memfoot but being able to loop up things

#

Animancer all the way

rare nymph
somber nacelle
#

doing that itself wouldn't cause any errors. you probably have an infinite loop

rare nymph
#

i think so

potent sleet
rare nymph
#

how do I stop the simulation if I can't open the editor

somber nacelle
#

kill the process

potent sleet
rare nymph
potent sleet
#

or wait till your memory gets all eaten up and crash xD

desert shard
#
        int numOfColliders = Physics.OverlapSphereNonAlloc(transform.position, explosionRadius, explosionHits);

        for (int i = 0; i < numOfColliders; i++)
        {
            IDamageable damagable = explosionHits[i].GetComponentInParent<IDamageable>();
            if (damagable == null || !hitSkeletons.Add(damagable)) continue;

            damagable.TakeDamage(damage);
        }```

is there an alternitive to this? I don't like pre assigning an array to 64 etc, esp what if the colliders filled do not contain the component I want (imagine theres like 50 `IDamageable`) within the overlap area, but only 10 get picked up coz of other colliders, that's quite bad
#

is there an alternitive? (increasing the allocated array size is not an option)

somber nacelle
#

layermask to prevent extraneous colliders from being included

desert shard
#

oh shit, I didnt even know

fresh forum
#

Why does OnCollisionEnter2D not work?

    void OnCollisionEnter2D(Collision2D other)
    {
        Debug.Log("COLLISION");
        if (other.gameObject.tag == "BoxesTag")
        {
            box.enabled = true;
        }
    }
somber nacelle
#

also keep in mind that Rigidbody2D is not a collider itself, you will also need a collider on that object (or one of its child objects)

fresh forum
#

oh

#

Right

#

I have to check those colliders too

#

hm

#

IDK

#

Nothing seems off on those colliders

somber nacelle
#

then click the link and go through those steps

fresh forum
#

Im doing that rn

#

I might have a solution

placid ridge
#

I'm trying to build my game, but the touch input breaks when it's built, and i don't know why. The touch of my script only works on Unity Remote, but not the editor nor build app. Here is my code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class DrawingScript : MonoBehaviour
{
    public float inkMax = 100f;
    public float inkCurrent;
    public float inkBeforeCalc;
    public int maxDrawings = 2;
    public float drawOffset;
    public GameObject linePrefab;
    public Tilemap tilemap;
    private LineRenderer[] lineRenderers;
    private EdgeCollider2D[] lineColliders;
    private int currentDrawing = 0;
    private Vector3[] linePositions;
    private bool isDrawing = false;

    void Start()
    {
        // initialize the array of line renderers
        lineRenderers = new LineRenderer[maxDrawings];
        lineColliders = new EdgeCollider2D[maxDrawings];
        for (int i = 0; i < maxDrawings; i++)
        {
            GameObject lineObject = Instantiate(linePrefab);
            lineRenderers[i] = lineObject.GetComponent<LineRenderer>();
            lineRenderers[i].positionCount = 0;
            lineColliders[i] = lineObject.GetComponent<EdgeCollider2D>();
        }
        linePositions = new Vector3[0];

    }```
#

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                if (inkCurrent <= 0)
                {
                    inkCurrent = 0;
                    inkBeforeCalc = 0;
                    isDrawing = false;
                    return;
                }
                // start drawing a new line
                isDrawing = true;
                linePositions = new Vector3[0];
            }
            else if (touch.phase == TouchPhase.Moved && isDrawing)
            {
                if (inkCurrent <= 0)
                {
                    inkCurrent = 0;
                    inkBeforeCalc = 0;
                    isDrawing = false;
                    return;
                }
                // check if the touch is over a non-colliding tile
                Vector3 worldPoint = Camera.main.ScreenToWorldPoint(touch.position);
                Vector3Int cellPosition = tilemap.WorldToCell(worldPoint);
                TileBase tile = tilemap.GetTile(cellPosition);
                if (tile != null && !TileIntersectsCollider(worldPoint))
                {
                    // add to the current line
                    Array.Resize(ref linePositions, linePositions.Length + 1);
                    linePositions[linePositions.Length - 1] = Camera.main.ScreenToWorldPoint(touch.position + new Vector2(0, 0));
                    linePositions[linePositions.Length - 1] = new Vector3(linePositions[linePositions.Length - 1].x, linePositions[linePositions.Length - 1].y, drawOffset);
                    lineRenderers[currentDrawing].positionCount = linePositions.Length;
                    lineColliders[currentDrawing].points = linePositions.toVector2();
                    lineRenderers[currentDrawing].SetPositions(linePositions);```
#

                    inkCurrent = inkBeforeCalc - calculateLineLength(linePositions);
                }
            }
            else if (touch.phase == TouchPhase.Ended && isDrawing)
            {
                // finish drawing the current line
                isDrawing = false;
                currentDrawing = (currentDrawing + 1) % maxDrawings;
                inkBeforeCalc -= calculateLineLength(linePositions);
                inkCurrent = inkBeforeCalc;
                if (inkCurrent <= 0)
                {
                    inkCurrent = 0;
                    inkBeforeCalc = 0;
                    isDrawing = false;
                    return;
                }
            }
        }
    }
    float calculateLineLength(Vector3[] linePositions)
    {
        float lineLength = 0f;
        for (int i = 0; i < linePositions.Length - 1; i++)
        {
            lineLength += Vector3.Distance(linePositions[i], linePositions[i + 1]);
        }
        return lineLength;
    }
    // helper method to check if a point in world space intersects with the collider of the Tilemap
    bool TileIntersectsCollider(Vector3 worldPoint)
    {
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
        return hit.collider != null && hit.collider.GetComponent<TilemapCollider2D>() != null;
    }

}



public static class V3Extention
{
    public static Vector2[] toVector2(this Vector3[] v3)
    {
        return System.Array.ConvertAll<Vector3, Vector2>(v3, getV3fromV2);
    }

    public static Vector2 getV3fromV2(Vector3 v3)
    {
        return new Vector2(v3.x, v3.y);
    }
}```
somber nacelle
#

please use a bin site to paste large blocks of !code 👇

tawny elkBOT
#
Posting code

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

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

dull yarrow
#

I am having a problem:
I have a item class and a Equipment class that have the item class as inheritance
In my Gameobject i have a item reference that i can place my equipment item
And i want to use for exemple a function that uses the Equipment item -> useItem(Item item)
The problem here is that i cannot use the Equipment class features
How do i turn around on this?
I cannot create a Equipment reference on my game object because other types of items will be in that reference too

fresh forum
#
public class CollisionHandler : MonoBehaviour
{
    public BoxCollider2D collider;

    // Start is called before the first frame update
    void Start()
    {
        collider = gameObject.GetComponent<BoxCollider2D>();   
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        switch (other.gameObject.tag)
        {
            case "BoxesTag":
                {
                    collider.SendMessageUpwards("GetBox"); 
                    break;
                }
        }
    }
}

still nothing working

#

What its colliding with

somber nacelle
#

you have a rigidbody2d on one of those objects, right? and they are on layers that can collide?

fresh forum
#

They are all on the default layers

#

they can collide too

somber nacelle
#

you're looking at the physics 2d settings, not the physics settings?

fresh forum
#

Yea

somber nacelle
#

okay and you have a rigidbody2d on one of the two objects, right?

fresh forum
#

yea

#

ooh wait

fresh forum
#

this is the collider attached to thhe player

#

And this is for the other one

somber nacelle
#

your rigidbody is static. two static colliders do not produce a collision/trigger message

fresh forum
#

But doesnt that need 2 rigidbodies?

somber nacelle
#

you need at least one non static rigidbody to produce a trigger message

limber cape
#

Do you guys know where I should go for a sprite issue? is that in graphics? Or can I get some help here?

somber nacelle
#

read the page i linked next time

limber cape
#

It looks like one the sprites just bugged and became this pink color

fresh forum
#

I also had to tick this

limber cape
#

like a purple and pink type

somber nacelle
#

that doesn't matter. the rigidbody is static

fresh forum
#

Yuh

#

I set it to dynamic

limber cape
#

I have 0 clue as to what can solve this:

#

I don't even know what happened to one of the sprites for it to just turn pink

fresh forum
#

oohhh

#

damn

#

No the right channel for this

somber nacelle
limber cape
#

mmmm I did perhaps do that a minute ago. How can I solve this?

#

also where's the right channel then

somber nacelle
stone echo
#

can unity detect collisions if im manually updating the positions?

#

i have one object manually moving left (position -=1) and another moving right (position +=1), will the oncollisionenter function detect the collision?

#

right now my code for whatever reason isnt detecting collisions and im not sure if its because im manually moving objects or something else

hexed pecan
#

MovePosition might work.
Transform.position does not

#

Or if it does, it is pure chance

somber nacelle
#

you need a rigidbody on at least one of the objects for collision messages to work

#

and if you have a rigidbody you may as well move using that instead of teleporting it via the transform

hexed pecan
#

Yeah, sounds like you might as well use rigidbody.velocity to move them at a constant speed

lost night
#

Is there a difference between loading the scene the first and the second time?

ashen yoke
#

what happens?

lost night
#

The first time i load it everything is fine

#

later i unload it and switch the scene

somber nacelle
#

i'm gonna guess you have a DDOL object that loses references because you change/reload the scene

lost night
#

When i load it aigan a object is not existant anymore which executes crucial code

ashen yoke
#

a singleton?

lost night
#

It is an dont destroy on load object thoug

#

A singleton?

ashen yoke
#

off to google whats a singleton

somber nacelle
#

could also show relevant code and errors

lost night
#

Should be a singleton

somber nacelle
#

so are you expecting us to magically know your code to provide an answer or do you want to maybe share relevant code and errors so i can helpfully point out for a second time that when you reload a scene the DDOL object won't keep the same references to non-DDOL objects because they are different objects

ashen yoke
#

if it is a singleton most likely you are not properly cleaning up the static field

#

as a result the gameobject is destroyed but the wrapper is left in the field and doesnt equate to null

#

but yeah, all that is just fart in the wind until you show the code

lost night
#
if(isPlayer)
            {
                NetworkClient.Disconnect();
                
                string path = Application.persistentDataPath + "/saves/soul.book";
                File.Delete(path);

                Debug.Log(path);

                if(isServer)
                {
                    NetworkServer.Shutdown();
                }

                SceneManager.UnloadScene("Server");
                SceneManager.LoadScene("CharacterCreationMenu", LoadSceneMode.Single);
            }
somber nacelle
#

!code

tawny elkBOT
#
Posting code

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

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

ashen yoke
#

this doesnt seem relevant to your issue

lost night
#

Thats why i am asking here Xd

somber nacelle
#

please provide relevant errors and the code the error points to

#

preferably the entire class where the error happens

lost night
#

I am not getting an error, it is just a behavior of the code i cant explain my self so far

somber nacelle
#

if you cannot even explain what the issue is then how do you expect anyone else to know what the issue is and how to fix it?

#

especially since you aren't even providing the full context

ashen yoke
#

so do you have a singleton?

lost night
#

I think the object which dissapears is a singleton

solemn raven
#

hi,
is it possible to lerp through multiple colors at the same time to result something like a gradient rainbow color ?
i only know how to mix 2 colors together
Color.Lerp(color1, color2, ratio);
but houw about 6 ?

#

the expected results is to be like that

somber nacelle
ashen yoke
#

but i dont know for sure

somber nacelle
#

but yeah, it probably won't look too great just lerping like that

solemn raven
#

hmm , I did try the loop solution before i asked and yea the end result is just blending of 2 colors.

#

so is theres any tool that can do it ?

ashen yoke
#

some third party libraries maybe

#

color mixing is a whole science in itself afaik

somber nacelle
ashen yoke
#

because in code its just numbers, which dont work nicely with human eye perception

hollow stone
solemn raven
solemn raven
hollow stone
#

Then it's the Hue value you want to change.

cobalt wave
#

I think jaws proposed the best solution

#

Hue let's you get the full spectrum and pin point the exact color you want and when

solemn raven
#

I'll try it out
@hollow stone thanks a lot 🙂

hexed pecan
#

@solemn raven Since you said this

i only know how to mix 2 colors together
I wanna point out that Gradients are a thing too and have a nice editor
https://docs.unity3d.com/ScriptReference/Gradient.html
You would just set it up in the inspector or via code, then sample it with Gradient.Evaluate

#

But yes you want HSV for the rainbow

solemn raven
#

i'll try the HSV

hexed pecan
hollow stone
hexed pecan
#

Yep, as I said, for this particular effect using Hue is more robust

#

Just kinda sounded like he wasn't aware of gradients

young wigeon
#

I'm trying to use "Hinge Joint 2D" to make the arms for my character flop around while they move but they aren't affected by physics

somber nacelle
#

do they have rigidbodies?

young wigeon
#

yeah

potent spruce
#

Are the constraints frozenm?

young wigeon
#

for the actual body yes but not for the arm

trim rivet
#

Any tips on preventing splash damage from going through walls ?

somber nacelle
#

are the rigidbodies Dynamic rather than kinematic or static?

trim rivet
#

raycasting to check wether level geo is in the way yieds very poor results

young wigeon
somber nacelle
woeful slate
#

I'm a bit confused. Shouldn't imports be handled automatically?

#

Trying to import the character class from my Entities folder

somber nacelle
#

you're using an asmdef, you need to reference the assembly that the Character class is in

woeful slate
#

what's an asmdef?

#

How would I import the assembly that the character class I made is in?

primal wind
#

Is it in a namespace? i can see a .cs file

somber nacelle
# woeful slate what's an asmdef?

oh even better, it looks like you're using an asmdef only for the Scripts folder for whatever reason. is this code you just yoinked from somewhere? is that why you somehow have an assembly definition that you don't know about?

woeful slate
somber nacelle
woeful slate
#

and it told me to just post the files in Assets

somber nacelle
#

either way though, just delete the asmdef file and it should work just fine

woeful slate
somber nacelle
woeful slate
#

like so?

somber nacelle
#

yes

woeful slate
#

The type or namespace name 'NativeWebSocket' could not be found (are you missing a using directive or an assembly reference?) [endel.nativewebsocket]csharp(CS0246)

#

i get this now when I try to import it into my custom client

somber nacelle
#

click the asmdef file in unity and make sure it has the automatically referenced box selected

primal wind
#

Wait can you import Javascript libs in Unity?

somber nacelle
#

i'd imagine that's probably for the webgl support

strong wing
#

Hey folks, using the XR Interaction Toolkit, is there a way to replace a grabbed object with a different one?

woeful slate
#

oh jk, it works, just needed to restart unity and omnisharp

strong wing
woeful slate
somber nacelle
#

ah, the Character class is also not public

woeful slate
heady iris
#

the error is complaining that the type of the field isn't going to be visible to everyone who has access to the field

marsh hawk
#

I'm trying to make it so that the red rectangle will be clamped from 90 to -90 on the while looking at the mouse on the left side. However, the rectangle will only look to the right side. Switching the 90 and -90 only makes the rectangle look at 90 or -90. Does anyone know how I could solve this?

solemn raven
# hollow stone You want to blend the HSV values.

hi ,
i couldnt get it to work , could you help me setting it up correctly ?

Color BlendColors(Gradient gradient){
Color result = default;
float colorCount = (float)gradient.colorKeys.Length;
float hueSum = 0f;
foreach (GradientColorKey colorKey in gradient.colorKeys)
{
    Color.RGBToHSV(colorKey.color, out float hue, out float saturation, out float value);
    hueSum += hue;
}
float averageHue = hueSum / colorCount;
result = Color.HSVToRGB(averageHue, 1f, 1f);
return result;
}

is this how we suppose to do it ?

somber nacelle
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

hollow stone
upper pond
solemn raven
#

it doesnt make sense to me , i think i dropped the ball somewhere

upper pond
#

anyone know how if theres an efficent way of making UI for any sort of counter(health, ammo, stamina) that essentialy displays the same ammount of sprites as the counter shows? example is i have 3 bulets so there is 3 bullet sprites at the bottom of my screen indicating the ammount of ammo i have. i shoot one and now there is only 2 bullets.

hollow stone
upper pond
#

ther is a way where you can do it like ```if(bullets == 3)
{
bulletSprite3.setActive(true);
}
else {
bulletSprite3.setActive(false);
}//repeat for sprite 2 and 1

solemn raven
hollow stone
solemn raven
# hollow stone But what are you blending by?

im looping throw a list of UIVertex which referes to the vertexs of an image and applying each vertex.color to the result of the function , that sounds odd to me , not sure if that is the right way to do it

hollow stone
solemn raven
#

i have very limited experience with shaders and colors in general , but i have heard that wt could blend multiple colors via code, if we somehome told the code on the far left for example to be blue and gradually change to pink after 20% of its width then red .... then finally yellow , that sounds like a plan i just dont know how to do it ,

heady iris
#

i'd suggest lerping a hue value

#

and then using that to compute colors

#

consider Color.HSVToRGB

#

it converts a hue, saturation, and value to a Color

#

hue is the kind of color it is, saturation is how strong the color is, and value is how bright the color is

solemn raven
heady iris
#

there is nothing "special" here

#

you want a range of hues

solemn raven
#

i thought that is what i did with the code above

#

but it doesnt work

heady iris
#

Color.HSVToRGB(0f, 1f, 1f) will spit out red

#

oh, you're using RGBToHSV there?

#

lemme have a look

solemn raven
#

sure 🙂

heady iris
#

averaging hues is not meaningful

#

just do something like this

solemn raven
#

yeah it gave me colors that was not on the gradient at all lol

#

some of which were too dark

heady iris
#
float t = 0;
while (t < 1f) {
  Color color = Color.HSVToRGB(t, 1f, 1f);
  t += 0.05f;
}
#

this will compute 20 colors

hexed pecan
#

Though, you dont want a value of 1

heady iris
#

going through the usual random

hexed pecan
#

As it will be white

heady iris
#

wait, is that value or lightness

#

i think that'd be lightness

hexed pecan
#

HueSaturationValue

heady iris
#

as in, lightness would give you white

#

oh, I'm familiar with..."HSB". thanks, Photoshop

#

ah, okay, I had it right there

#

the HSL model gives you white with a lightness of 1

cobalt wave
#

yea you did it right

heady iris
#

the HSV model gives you colors with a value of 1

#

i love color models

#

i kind of get L*a*b

#

L*a*b is pretty great for blending between colors, actually. I used it once to program my smart lights...

hexed pecan
heady iris
#

i'd have absolutely tripped on that if it was HSLToRGB

hexed pecan
heady iris
#

i didn't actually think about it until now, lol

hexed pecan
#

Didnt notice that you need to have 0 saturation to have a white output

heady iris
#

especially because Photoshop talks about "HSB"

#

i think it's just HSV

#

probably

#

now let's talk about gamma curves and sRGB

#

🫠

hexed pecan
#

Pls no

cobalt wave
#

what even is gamma though

#

isn't that just the lightness value?

#

but like

#

fancier

solemn raven
#

im trying to make sense of all that
btw @heady iris thx so much for sharing , im starting to actually get some results

float x;
while (t < xf){
ver.color = Color.HSVToRGB(t, 1f, 1f);
t += 0.05f; }

so i have included (x) in my forloop and gave x different values just to see different results
when x = 1 this is what i got

#

where is the blue ? 😄

#

nvm found it 0.75

heady iris
#

yeah

#

HSL (for hue, saturation, lightness) and HSV (for hue, saturation, value; also known as HSB, for hue, saturation, brightness) are alternative representations of the RGB color model, designed in the 1970s by computer graphics researchers to more closely align with the way human vision perceives color-making attributes. In these models, colors of ...

#

that's where I stole the figure from, lol

#

HSL is closer to how paints work

red scarab
#

Any reason I shouldnt put rigidBody on the environment, instead of the player?

#

I've got Players, and Enemies - they don't need to collide, but both should collide with environment. So, I can have a RB on Player and Another on Enemy, -or- I could put 1 on the environment...

hexed pecan
#

It needs to be on the moving objects

somber nacelle
#

why would you want the environment to have physics?

hexed pecan
#

Simply put

heady iris
#

you COULD put a kinematic rigidbody on the environment, I guess

red scarab
hexed pecan
#

You could, still need a rb on the characters though

heady iris
#

but then you'd need a non-kinematic rigidbody on the player anyway

somber nacelle
#

well making it static means you'd still need a rigidbody on your characters for collision messages

rain minnow
#

If the environment isn't moving around being affected by everything, then static or kinematic (in certain instances) are fine . . .

somber nacelle
hexed pecan
#

Maybe for continuous collision detection you might wanna add a RB to some walls

somber nacelle
#

static rigidbody counts as static in that matrix

heady iris
#

ooh, this is 2D

somber nacelle
# heady iris ooh, this is 2D

grid is basically identical though so it doesn't make much difference here. the resource i linked just has a slightly better explanation about the grid than the docs would provide

heady iris
#

yeah

ancient cloak
#

anyone ever connect a unity game to a local .net core process using websockets? I manged to get a discord bot doing something i wanted but i had to end up doing it in .net core after like 8 libraries failed to implement what it claimed to, and now i'm struggling to get that data to the game's runtime

#

i was thinking i could just run the .net core app as a process and monitor its output

#

I tried using nativewebsockets on the unity side to create a socket on 8080, and used websharp on the .net core app to connect to the socket on 8080 but the unity app hangs while creating the socket and the .net core app fails to connect

deft cape
#

any ideas on how to get this working? I want to make a soft reference to "TriggerFunc" so I can call it across multiple different components iwthout having to name each one

heady iris
#

i do not know what "soft reference" means

#

do you have a specific class that has a function called TriggerFunc?

deft cape
#

sorry I'm new to unity

heady iris
#

or do you have several unrelated classes that all have a function called TriggerFunc?

deft cape
heady iris
#

you need to create an interface, then

deft cape
#

mfw when I asked my friend if interfaces were in unity and they told me no:

heady iris
#

well, interfaces aren't in "unity"

#

they're a C# thing

#

but I would agree that you can use interfaces when working in unity :p

deft cape
#

how hard you think interfaces are to setup cause im in game jam and im debating just manually hard coding in each reference cause of time

ancient cloak
#

literally trivial

ancient cloak
#

the methods you want as part of the contract, define them in the interface, inherit from the interface, and you're off to the races

heady iris
#

indeed

#

you won't even have to change anything in the concrete classes

#

other than declaring that they implement the interface

#

then, you can use the interface type in place of that Component type in your code

ancient cloak
#

an interface is literally just that, like the plug/socket combo's in your house are interfaces

heady iris
#

as Stropheum said, it's a "contract"

ancient cloak
#

you don't need to be an electrician but you can arbitrarily and modularly wire any electrical device into your home because you just rely on the interface

heady iris
#

it's a promise that you can do X Y and Z

#

or, in this case, just a promise that you can do X

tropic quartz
#

I'm a nublet and even I find interfaces relatively easy to use, shouldn't be a problem.

deft cape
#

I came from UE5 so I knew what interfaces were, I just asked my friend if unity implemented them when we were setting up interaction system and he told me no so I just ran with it and now im like "ok surely there has to be an easier way thats at least similar" lmao

ancient cloak
#

in this case, it would be like

public interface IWallSocket
{
  public void PlugIn();
  public void Unplug();
  public void SetActive(bool isActive);
}
#

every language has interfaces and they're all pretty much the same

#

only thing is in unity (and i hate this) you can only serialize concrete types to the inspector

#

which is fucking annoying

heady iris
#

[SerializeReference] correctly handles abstract classes

#

although you have to write your own property drawer

#

zoop

ancient cloak
#

abstract classes but not interfaces

#

which is kind of pedantic but it fucks with the coding by contract paradigm

deft cape
ancient cloak
#

no you would tell your class to implement it

#
public class DishWasher : IWallSocket
{
  public void Plugin()
  {
    //do things a dishwasher does when you plug it in
  }
  public void Unplug()
  {
    //do unplug things
  }
  public void SetActive(bool isActive)
  {
    //turn the dishwasher on or off
  }
}
#

so then you can have like a house electrical controller that does something to the effect of

heady iris
#

i plugged the dishwasher into the natural gas pipe

#

💥

ancient cloak
#
public class HouseElectricalSystem : Monobehaviour
{
  private List<IWallSocket> _homeAppliances;
  public void OnPowerLoss()
  {
    _homeAppliances.ForEach(x => x.SetActive(false));
  }
}
ancient cloak
#

so the house electrical system doesnt give a shit if it's a dishwasher, a vibrator, a stove, your phone. all it cares is that it's something you plug in

heady iris
#

no static type checking

ancient cloak
#

javascript is an objectively bad language

#

if anyone disagrees, ask them where the triple equals sign came from

#

they had to add === because == didn't work LUL

heady iris
#

typescript, my beloved

#

anyway

#

is anything unclear on interfaces right now?

rain minnow
deft cape
heady iris
#

yeah, if you create a new C# script in unity, it's pre-filled with some stuff

ancient cloak
#

my workaround is usually like some kind of composable attribute system for like-things

heady iris
#

throw that out and write an interface

ancient cloak
#

and then i can make scriptable object instances for each configuration

heady iris
#

i usually just create a new file from my code editor

ancient cloak
#

good luck on your game jam btw

#

rule of thumb is get it done. if you catch yourself trying to be clever in a game jam your game is gonna suck

#

i've been burned multiple times getting inspired to make a really elegant system

deft cape
# heady iris throw that out and write an interface

so I do just make a C# script and chuck it all out ye?
and also I don't need to attach the interface like a component right I can just add it in the code to the script for the object in the class section ye?

ancient cloak
#

yep

#

literally make it look like this

heady iris
#

correct: the interface is not a component

ancient cloak
#
public interface IMyInterfaceThing
{
  public void MyDeclaredMethod1();
  public void MyDeclaredMethod2();
  //and so on
}
#

convention is to previx interfaces as generally like I(Verb)

#

like ICompressable, or ILovable

#

those are adjectives

tropic quartz
#

Yeah, I think you actually can't attach an interface to an object even if you try.

rain minnow
#

The interface does not physically exist within Unity. You just implement it from a class . . .

deft cape
# ancient cloak i've been burned multiple times getting inspired to make a really elegant system

me being proud and making a text based system for dialogue despite it not being the wisest idea:
ima just try to finish then polish later when more time

Funnily enough first time using unity.
fourth game jam tho, first jam I did was first time using UE5, then second was a collab with a friend using their preferred engine (godot which I forgot how to use cause i didnt for a year or so) and third was solo UE5 again

this time im using unity cause I thought what the hell yknow might as well learn somethin and mah friend refuses to try other engines so lol

deft cape
#

success ty very much everyone who helped

tulip mauve
#

I need to display a bunch of spheres with a predetermined size and color at a bunch of different places in the world, without collision. I'm aware of GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Sphere);, but this creates colliders and instantiates a gameobject, when I just need the mesh since there are a lot of spheres. How can I achieve this?

tropic quartz
#

Would it be bad to just use the default unity sphere? And just set colors with material color value.
Wouldn't need colliders.

tulip mauve
#

how would I do that? GameObject.CreatePrimitive(PrimitiveType.Sphere); creates colliders by default and I feel like creating and immediatley destroying them is bad practice

tropic quartz
#

Just instantiate a regular gameObject prefab, with the meshrenderer using the sphere.

#

Oh. I guess you asked for pings. @tulip mauve

tulip mauve
#

no worries lol I saw it

#

Thanks, I appriciate it

shrewd plume
#

Hi, I was thinking of a problem, that I dont really know how to properly explain (because I dont really know how it works tbh), but it was about how unity deals with the registration of listenners to callbacks via interfaces (e.g. The input system Map class Callback interface with actions callbacks or the event system with Interfaces for each of the UI actions) where you just determines a contract via the interface and the class will listen for when something happens.
Is this someway achievable or, as I think it is, is more complicated and takes more "behind the scenes" work by unity for it to work properly?

sinful galleon
#

Does anyone know how to make a certain input a holdable button?

I’m making a platformer and it’s kinda ruining the flow of the game because I have to time my jump button every time I land, if I click too early it doesn’t input and makes for a worse experience.

Some help would be great

shrewd plume
somber nacelle
#

the event system uses either the Graphic Raycaster or Physics Raycaster to raycast from the mouse position and then it can just easily use TryGetComponent or something similar to call the interface methods

shrewd plume
#

In this case I think it makes sense, but event system has other events that don't necessarily use Graphic Raycaster (I think) like the IMoveHandler and the ISubmitHandler

somber nacelle
#

the EventSystem also has a reference to the currently selected object so it can easily call TryGetComponent to get the interfaces from the selected object and call the relevant methods

shrewd plume
#

Yeah, I would want to know some more about it though... its sad to don't really know if this kind of architecture has a name or somethin... 🫠

somber nacelle
#

there's literally nothing special about it other than what i've already described. the EventSystem uses the Physics Raycaster and/or Graphics Raycaster to get a reference to the object it should call the interface methods on

shrewd plume
#

I mean to make a system that uses Interfaces to register listenners, but I think this problem has other Middle mans other than just the interfaces. In the two examples that I mentioned there needs some other step for it to work properly, so I don't think it's a easy task

somber nacelle
#

you're implying that unity is doing something super special to call those methods on the components that implement the interfaces, but that isn't the case. the EventSystem has a reference to the object already so it's as simple as calling TryGetComponent on that reference to call the interface methods

#

you could use some sort of dependency injection and/or mediator pattern if you want to invoke events and have receivers react to the event without manually getting a reference to subscribe to the event

lethal plank
somber nacelle
#

can you share your !code correctly

tawny elkBOT
#
Posting code

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

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

quartz folio
lethal plank
#

oh i j

#

copy paste moment

#

thank you

stuck robin
#

does anyone know what the criteria for an object being droppable is? this is in relation to the IDropHandler interface.

#

like I have an inventory slot gameobject and want to fire the callback every time a UI object is dropped onto it but am unsure if this is correct use case (i think it is but im uncertain).

latent latch
#

The IEndDrag is actually just fluff which you usually just use to reset displayables

#

Oh, huh I swear there was a ton more documentation here. Maybe need to revert to the previous version documentations, but the idea is you need both an IDragHandler and an IDropHandler at minimum; everything else is just fluff. I'm pretty sure you can put an IDropHandler without an IDragHandler on your scripts if you just want that gameobject to receive drops callbacks without enabling it to send drag callbacks.

#

Oh, and the object needs to be able to receive raycasts, so UI stuff needs their raycasts can be blocked box ticked

clear pelican
#

someone here using mapbox API? i make a custom map on mapbox i put place’s with names then how to make it searchable?

swift falcon
#

So basically I have an emailing system in my app, like it sends an actual email through Gmail

But in the code, someone can easily find the "App Password" from that email.
Now ofc im not using my main email, im using a dummy empty email to send the messages out but I still dont want people getting that information

How can I hide it or encrypt it somehow?

deep willow
#

im using navmesh and when an agent gets close to the destination, it slows down. how do i make it move at the same speed until it hits the destination?

turbid surge
deep willow
#

okay ill try that

#

also i want the agent to immediately change direction when the destination changes, because right now it slows, then slowly changes direction

turbid surge
#

By change direction slowly you mean rotates slowly, right?

deep willow
#

yeah i guess so

#

must be

turbid surge
#

try also adjusting the agent.angularSpeed

deep willow
#

okay

#

the stopppingDistance didnt change anything

#

i unticked AutoBraking too to see if that made it work

#

do i just set them in start method?

turbid surge
#

yes

deep willow
#

hmm yeah im doing that

#

no dice tho

#

weird

knotty sun
#

you should have autoBraking off and you can set the agent velocity to keep the speed constant

deep willow
#

ill try that

stuck robin
civic fern
#

im trying to make a grid, and im using a script, but its getting confused it keeps going back to the beginning after its created a somewhat grid

#

this is what it makes

#

heres my code

#
public class GridScript : MonoBehaviour
{
    public float gridSize = 10f;
    public float gridSpacing = 1f;

    void Start()
    {
        LineRenderer lineRenderer = GetComponent<LineRenderer>();

        int numLines = Mathf.FloorToInt(gridSize / gridSpacing) + 1;
        lineRenderer.positionCount = numLines * 2;

        float gridStart = -gridSize / 2f;
        float gridEnd = gridSize / 2f;
        int lineIndex = 0;

        for (float i = gridStart; i <= gridEnd; i += gridSpacing)
        {
            // Add vertical line
            lineRenderer.SetPosition(lineIndex, new Vector3(i, gridStart, 0f));
            lineIndex++;
            lineRenderer.SetPosition(lineIndex, new Vector3(i, gridEnd, 0f));
            lineIndex++;

            // Add horizontal line
            lineRenderer.SetPosition(lineIndex, new Vector3(gridStart, i, 0f));
            lineIndex++;
            lineRenderer.SetPosition(lineIndex, new Vector3(gridEnd, i, 0f));
            lineIndex++;
        }
    }
}
#

im assuming its the for loop logic

#

maybe use a for loop for each vertical and horizontal

quartz folio
#

You use one line renderer. Line renderers draw one continuous line

civic fern
#

seperately

#

so id need to use lets say 2 linerenderers for vertical and horizontal

#

that makes sense

#

let me try it rq

civic fern
#

any clue why code takes long as hell to complile

fresh forum
hexed pecan
#

Looks fine to me tbh

crystal holly
#

hey everyone, i am playing around with Netcode for GameObjects and want to deploy a dedicated server build to my Azure Windows VM. I can't seem to connect though. I added an inbound port rule for port 7777 but no success connecting. Does anyone have any resources on how to configure a Azure VM in order to allow connections?

fresh forum
hexed pecan
fresh forum
#

the camera is supposed to stop moving when the skeleton hits that

#

but for some reason it happens way earlier

hexed pecan
#

So how was any of that apparent from your original question

#

How are you detecting that the skeleton hits that box?

fresh forum
#

:///

fresh forum
#

and the skeleton has a rigidbody trigger

#

attached to that trigger

#

is a script

#

I can send it

lean sail
#

Triggers dont stop colliding objects I thought

#

Oh I misunderstood the issue, mobile issue

hexed pecan
fresh forum
#

1 min

#

Here is the method(s) it calls

#
    IEnumerator DieAsync()
    {
        camScript.enabled = false;
        yield return new WaitForSeconds(3f);
        // TODO: FADE
        SceneManager.LoadScene("MainGame");
    }

    void Die()
    {
        Debug.Log("Ran kill");
        StartCoroutine(DieAsync());
    }
#

Ignore the bad code, I'm doing a game jam and I don't have time to write good code lol

hexed pecan
fresh forum
hexed pecan
#

Do some debugging and find out why

fresh forum
#

Im trying bruh

#

How should I be debugging?

hexed pecan
#

Log what is triggering the OnTriggerEnter2D, log the tag too

fresh forum
#

Ok

lean sail
#

You can also pause when it collides to see where exactly it is

#

With debug.break

fresh forum
#

Wtf. Lemme check the collider

#

the red dot is where i collided, the green box at the bottom is where the LavaHitbox is

lean sail
#

Is the lava not just colliding with the green box?

fresh forum
#

The lava itself doesnt have a collider

#

Also this.

#

I've tried making sure that the lava can only colldide with the player

hexed pecan
#

Show me the inspector of LavaHitbox

fresh forum
#

The lava and the lava hitbox are separate objects.

hexed pecan
fresh forum
#

What if it's the camera?

hexed pecan
#

Man, this switch statement in triggerenter is such spaghetti

fresh forum
#

but that wouldn't make sense cuz it has no collider ://

fresh forum
hexed pecan
fresh forum
#

Its colliding with yea

hexed pecan
#

If it was the camera then it would print that

fresh forum
#

Im printing the object its collding with

#

not the actuall collider object

hexed pecan
#

other is the actual collider

#

So idk what you mean

fresh forum
#

So is it not what i'm colliding with?

hexed pecan
#

Yes?

fresh forum
#

But the script isnt attached to the lava hitbox

hexed pecan
fresh forum
#

Idk bruh

hexed pecan
#

Isnt the script on the player?

fresh forum
#

yea

light beacon
#

hi lads, do know how to wrap around a world map, as in go from one edge to the other seamlessly? In a 2D RPG with tile maps atm. Currently, I have it where you basically have a duplicate map and move it right next to the current one, and they leapfrog each other depending on which edge you go on. I was wondering if theres a better way

lean sail
# fresh forum

The "other" variable gives you the object that you hit. You hit the lava according to your debug, not the camera

cold parrot
lean sail
fresh forum
dusk apex
#

Did the log say it hit the lava object?

fresh forum
lean sail
#

Ok on that trigger function, remove the switch because it is going to force the debug to only break when it hits lava from what I see. Have it print when it collides with anything other than the ground

#

Or when it collides with the box specifically

#

I assume the only reason it printed lava was because your character fell in there after it already died

dusk apex
#

Then it likely did. Maybe log the point of contact and use the overloaded second parameter in log to highlight the object in the hierarchy on single click of the log. cs Debug.Log($"...", other.gameObject);

hexed pecan
lean sail
#

That's what I'm saying

fresh forum
#

It still prints die and lava without the character dying

lean sail
#

Because your function is doing some switch statement and comparing it to lava

#

Did u show the whole trigger function before?

fresh forum
#

yea

fresh forum
#

The switch may actually be the problem

#
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Lava")
        {
            {
                Debug.Log("Hit lava");
            }
        }
    }
lean sail
#

Yes that's what I was trying to say. You are only debugging when it hits lava..

fresh forum
#

This works much better

#

but how could the switch cause the character to die

#

before touching lava

#

?

lean sail
#

Wait wasnt it supposed to die when it hit the green box, I thought u said that before

dusk apex
#

Use the compare tag function instead of string comparison

fresh forum
#

yea

lean sail
#

Or that's when the camera is supposed to not follow

light beacon
dusk apex
dusk apex
lean sail
#

You need to debug more than just lava otherwise your character might die, not pause the game, fall into lava, and then debug/pause

fresh forum
#

but if its a better solution then sure lol

fresh forum
lean sail
#

Does your debug still say lava

fresh forum
#

yup

#

im jsut doing what you said

#

and debugging more shit

lean sail
#

Then your collider is just messed up or the objects that your script is on is jumping all over the place

cold parrot
lean sail
fresh forum
#

by script

lean sail
#

What's the white thing in the lava, is that the game object that has the on trigger function?

#

Or where is that

fresh forum
#

thats a light

#

but it has no tags or collisions

lean sail
#

Sorry hard to see on mobile I just couldnt tell

fresh forum
dusk apex
#
Debug.DrawLine(transform.position, other.transform.position, Color.green, 5.0f);```
lean sail
#

It's likely the line would be extremely small since the game object and other are touching

#

Would be the same thing as just following the game objects position every frame

hexed pecan
#

The line draws between origins, not contact points, so it should be visible

dusk apex
#

If anything, maybe you're looking at the wrong object - assuming the collider isn't on the skeleton.

lean sail
#

I believe he said its on an empty object on the skeleton somewhere above

dusk apex
#

I'm assuming that's where the fault lies.

lean sail
#

Yea that's why I'm saying to track the game object every frame, I'm thinking it's going flying around very often and falling down the tunnel into the lava very fast

#

Honestly now that I scrolled up I cant even find where he said that but regardless tracking it every frame will show the fault. It likely is just falling really fast

unborn flame
#

im having a issue where my bullets should be apearing as a constant stream but instead only spawn when i move the player. this is my code aswell ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.InputSystem;

public class Shooting : MonoBehaviour
{
public Transform shootingPoint;
public GameObject bulletPrefab;

private void Update()
{

    Instantiate(bulletPrefab, shootingPoint.position, transform.rotation);
  
}

}

#

i put it in the update so shouldnt a bullet instantiate every frame? It was woeking and doing that before.

winged tiger
heady iris
#

they are probably crashing into each other, yes

unborn flame
cobalt wave
cobalt wave
#

I don't feel like scrolling

fresh forum
#

Lemme see if I can find a summary for you lol

unborn flame
fresh forum
#

wtf is going on

#

I circled the skeleton

#

I removed the canvas, same thing

cobalt wave
#

also, exilon I have no idea why that's happening

#

are you sure nothing else in the scene has the tag of lava?

#

actually I would try commenting out the code that stop the camera movement and detects lava, maybe you already are doing it somewhere else and you just forgot?

heady iris
fresh forum
#

even though its not near it

cobalt wave
#

have you tried making the lava inactive and see if it still happens?

#

because that would just mean you put the lava tag on something else

heady iris
#

you should check what you're actually triggering, yes

swift falcon
#

Hey y'all! I am making my own version of Unity's PlayerPrefs, and i am using an encryption key to save and load data into a file. But right now the key is just a const readonly string. So if someone has a save file, they can share it. Is there any way to securely save a randomly generated key to use?

#

I thought about making another file, but that unneccerarely complicates things in my little script...

heady iris
#

using cryptography to encrypt your save file and thinking an extra save file is "unnecessarily complex" seem like contradictory ideas...

cobalt wave
inner bear
#

hi people

#

can anyone help me with my stuff

heady iris
#

don't ask to ask; just write your question

swift falcon
#

here is the script

cobalt wave
fresh forum
cobalt wave
#

disable it

inner bear
#

how do i control post processing 'color grading' value using slider

cobalt wave
#

the entire object

inner bear
#

from script

fresh forum
#

oh

swift falcon
inner bear
#

i just cant

#

access

swift falcon
#

it's just really jumbled

fresh forum
cobalt wave
# fresh forum oh

like, select it in the scene, and in the inspector, left to us name, click that tickbox so its empty

#

ye

#

now try running it

heady iris
#

i could destroy this scheme with a very basic chosen plaintext attack

#

(or even just known plaintext, really)

cobalt wave
swift falcon
heady iris
#

what is your end-goal here? what are you protecting against?

#

who is the adversary?

fresh forum
swift falcon
#

tried it but took me more time to debug then to make the entire script so i opted with the XOR operator

inner bear
#

also my unity is being like a beach. it doesnt react with trigger thing. i told it to disable kinematic but it dont want to. but it print the debug

cobalt wave
inner bear
#

all in the same class

#

-_

fresh forum
swift falcon
fresh forum
#

no collisions

cobalt wave
#

can you reanble the grid

#

and then try

#

reenable*

heady iris
#

what you've created here is the Vigenère cipher

fresh forum
#

yea

#

the grid is all cosmetic

cobalt wave
#

I know but please do

fresh forum
#

Alr dead

cobalt wave
#

maybe there is a tile in the grid that has the lava tag

fresh forum
#

did

cobalt wave
#

well

#

what happened?

swift falcon
fresh forum
#

nothing

cobalt wave
#

I need some feedback smh

fresh forum
#

no colission

#

bruh my spelling

#

is different

cobalt wave
#

there is still a level tho? you can still move your skeleton around and it collides with the ground?

#

you didn't disable everything right?

heady iris
# swift falcon i did not know that, cool :)

anyway, I don't really have any experience in the mobile space, but if you really want to prevent people from circumventing purchases, you'll need to store some data on the server side

#

where the user cannot manipulate it

cobalt wave
#

because I want to see if there is maybe some other collider that is triggering it

fresh forum
#

Everything is normal

#

except the lava

#

which is no-collide

swift falcon
cobalt wave
swift falcon
#

do you know any encryption method that is secure enough?

heady iris
swift falcon
#

any way to jumble up the key?

heady iris
#

sure, you can obfuscate it

#

just having a key file and a save file will already slow a lot of people down

swift falcon
#

alright

heady iris
#

i'm not familiar with mobile devices, but i'm pretty sure applications can have storage that nobody else (including the file browser) can see

#

which would also put up another hurdle

swift falcon
#

android has built in protection since the new updates to the persistentDataPath

fresh forum
heady iris
#

one thing that comes to mind is having a file that stores your purchases

fresh forum
#

idk for the life of me what to do

heady iris
#

rather than encrypting it, you would sign it: the server would use a private key to create a digital signature

#

the game would then only accept your purchases as valid if the signature validates

#

asymmetric cryptography, rather than symmetric cryptography (the fun is increasing exponentially)

swift falcon
#

the complexitity too

#

my english vocabulary does not know half the words lol