#archived-code-general

1 messages · Page 341 of 1

silent tapir
#

gotcha

quaint rock
#

up to you how you want to represent it, sure there are plenty knowledge or the topic around, this type of system is not exactly new

silent tapir
#

how would I utilize that 2d array though?

quaint rock
#

the 2d array represents each cell in the inventory grid, and what item is assigned to each cell, where 1 item might be assigned to many cells at once

silent tapir
#

Like I am not sure how an item is supposed to be in two slots at once

#

Because with a normal system I just keep the item as a child of the slot

quaint rock
#

break the problem down, first figure out a grid system, then how to click and drag to and from it with 1 item per tile

silent tapir
quaint rock
#

then how to effect multiple tiles at once

mellow grail
#

can someone please help? im getting the error "RPC method 'SwitchWeapon(String, Int32)' not found on object with PhotonView 1. Implement as non-static. Apply [PunRPC]. Components on children are not found. Return type must be void or IEnumerator (if you enable RunRpcCoroutines). RPCs are a one-way message." whenever i try to call the rpc in this script, both the script that sends and receives the rpc has a photon view and the rpc is listed on the rpc list.

#

I double checked the parameters too

silent tapir
#

the approach now for multiple tiles I need to figure out

#

@quaint rock so I got this gold I can drag around that is a 1x1, but then this rifle that is a 2x1. How should I child this? if I child it to a slot the slot next to it will obviously overlay over it.

quaint rock
#

would not make it a child of the cells, would just snap its position based on cell location

#

and each time something is dropped would update the array of which cells are occupied

silent tapir
#

gotcha

quaint rock
#

and while dragging someting around do the math to figure out which cells you are over and based on your items shape and are those cells occupied

silent tapir
#

okay

silent tapir
silent tapir
#

@quaint rock?

warm kraken
#

as my project grew this issue has become more and more common. unity gets stuck sometimes up to 5 minutes on this and im forced to terminate and restart unity once in at least 5 times after writing code and/or going into play mode. i tried assembly definitions but this issue still prevails. any advice would be ver welcome thank you in advance.

cosmic rain
warm kraken
#

i dont think i have many static classes or variables. maybe one. i know about that setting but i feared it would cause some negative side effect.

cosmic rain
lunar python
#

for me i just turned off domain reload and everything works just fine

strong oak
#

anyone know how to make ultrakill style bosses and ai?

#

or can anyone reccommend a video that'd help

thin aurora
woeful spire
fading umbra
#

I don't understand how to lerp my fps movement. How to lerp when the end position is not predicted.

leaden ice
#

Usually you would do something like a velocity simulation with acceleration

fading umbra
#

I see. I did use that at one point.

leaden ice
#

This isn't really a typical/correct Lerp usage either

knotty sun
#

ffs.

  1. Type in complete sentences like you have been told before
  2. Not a code question; Use the correct channel
  3. Whatever floats your boat
frank marsh
#

Hello, in a 3D project, my "OnCollisionStay" method is not called every frame, even if the rigidbody is awake, and moving. The research i did only mentioned setting "sleepThreshold" to 0, or keeping the rigidbody awake, and both of these solutions are useless.
Does someone had this problem before?

#

the method is called, it's just that it's not called regularly. I want this callback to be called every frame instead of every 10 frames or so. My detection mode is already set as "continuous"

#

already did

#

what do you mean by that, which timestamp?

heady iris
#

you should...not do this

#

this is going to screw up all of your game's physics

#

that will make physics update 10 times per second, rather than 50 times per second

heady iris
frank marsh
#

yeah, i wont change this value

heady iris
#

continuous collision detection helps to detect collisions that would otherwise be missed because you're moving too fast

heady iris
frank marsh
heady iris
#

Show your entire script !code

tawny elkBOT
frank marsh
#

actually, the only problem is that OnCollisionStay is called once for every 3 or 4 calls of the Update method, i'm affraid that the rest of code wont give much information

frank marsh
#

the collision stays between these calls, since no OnCollisionExit is called

heady iris
#

OnCollisionStay is called once per physics update.

#

It isn't called once per frame.

#

If your game is running at 150 FPS, you will get three frames per physics update at the default physics timestep of 0.02

frank marsh
#

how to make it called once per frame, is it possible?

heady iris
#

You can't.

#

That's not how Unity works.

#

If you want to be able to check if you're currently colliding in Update, set a bool field to true when the collision starts

#

and set it back to false when the collision ends

frank marsh
heady iris
#

I don't see the problem.

frank marsh
#

i could, yes, i'm just thinking if it's a problem, if the normal is changing between these calls

heady iris
#

It's not changing.

#

Physics happens once per physics update (as the name implies)

#

It doesn't matter if your game is running at 500 FPS. Physics is only calculated 50 times per second.

frank marsh
#

Thank you very much for these informations

#

i will change my code

scenic sigil
#

Hello, I have a problem with a Rigidbody. Basically, when I walk into another Rigidbody which is kinematic, my player character slides on top of it and when it gets off, it falls but very very slowly, so you are basically flying. I can provide any info, the Rigidbody for the player character is on screen.

heady iris
#

You could also use a particle system.

scenic sigil
#

Where is it?

heady iris
#

Show the code.

scenic sigil
# heady iris Show the code.
public class FirstPerson : MonoBehaviour
{
    [SerializeField] private Transform cameraTransform;
    [SerializeField] [Range(1f, 20f)] private float moveSpeed = 5f;
    [SerializeField] [Range(1f, 20f)] private float jumpPower = 5f;
    private Vector2 look;
    private Rigidbody rb;

    private void Awake()
    {
        rb = gameObject.GetComponent<Rigidbody>();

    }

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

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

    void FixedUpdate()
    {
        UpdateMovement();
    }

    private void UpdateMovement()
    {
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        Vector3 input = new();
        input += transform.forward * y;
        input += transform.right * x;
        input = Vector3.ClampMagnitude(input, 1f);

        rb.MovePosition(transform.position + (moveSpeed * Time.deltaTime * input));
        rb.velocity = Vector3.zero;
    }

    private void UpdateLook()
    {
        look.x += Input.GetAxis("Mouse X");
        look.y += Input.GetAxis("Mouse Y");
        look.y = Mathf.Clamp(look.y, -90f, 90f);

        cameraTransform.rotation = Quaternion.Euler(-look.y, look.x, 0);
        transform.localRotation = Quaternion.Euler(0, look.x, 0);
    }
}
heady iris
#

yeah, you're setting your velocity to zero every physics update

#

gravity doesn't work very well when you reset your falling speed 50 times per second 😉

#

Consider just setting the X and Z parts of your velocity vector based on move input

scenic sigil
heady iris
#

removing MovePosition entirely

heady iris
scenic sigil
#

Set x and z to what?

heady iris
#

the velocity you want to move at in those directions

#

probably just input.x and input.z (both multiplied by moveSpeed)

scenic sigil
#

How do I translate my MovePosition into that accounting for moveSpeed

heady iris
#

input has X and Z components that depend on how fast you're trying to move in the X and Z Directions

#

just don't multiply by deltaTime and you have a velocity instead of a displacement

scenic sigil
heady iris
#

Yep, that looks reasonable.

scenic sigil
#

Used Roblox syntax instead of C# for the new()

heady iris
#

Do you have X and Z rotation locked on the rigidbody?

#

I can’t quite tell what’s causing that

scenic sigil
#

Not only with the camera

heady iris
#

oh, it’s jitttering up and down

scenic sigil
#

Yup

heady iris
#

That is very weird. The Y position isn’t changing

#

Ah, one thing: set the camera rotation after rotating the entire player.

cosmic rain
#

Just mentioning a design pattern doesn't really explain what you have in mind.

scenic sigil
heady iris
#

since it is parented to the player

#

This got corrected on the next frame, as long as you stopped rotating the camera

scenic sigil
#

Also now that I'm not setting the velocity to 0 I don't fly because of the platform, but I can still slide up onto it

vagrant agate
#

layer collision matrix is one way

#

i mean to be honest, your trigger could work for both. just when it triggers with an object you want to destroy the bullet just do it.

simple egret
#

The main disadvantage with triggers is that, if your projectile is too fast, you experience tunelling where the bullet passes through the target without firing OnTriggerEnter.
And the disadvantage of regular colliders is that the projectile stops dead in its path at the first collision

#

The middle ground would be to ditch the collider entirely, and manually check for "collisions" with a Raycast between the position of the bullet on the last frame and the current position

#

This allows you to loop through the detected objects in your path and apply logic whether to stop the bullet or pass through

heady iris
scenic sigil
heady iris
#

that was vague yeah :p

#

select the object with the collider and show me it in the scene view, as well as the inspector

#

if the rigidbody is on a different object, show me that as well

heady iris
#

The player.

scenic sigil
#

The inspector doesn't fit in one image

#

What can I collapse

heady iris
#

just take multiple screenshots

scenic sigil
#

I squeezed all the necessary info in, only omitted my script and mesh filter

#

Ignore the jump power

#

It's unused

heady iris
scenic sigil
#

Lemme grab some footage

heady iris
#

It's possible that the capsule collider is causing a slight vertical force when it whacks into the wall

#

and since you're setting the velocity every physics update, it's like you're crashing into the wall at full speed 50 times per second

scenic sigil
#

Slight can't be enough for that

heady iris
#

Try this:

Vector3 movement = rb.velocity;
movement.y = 0;
movement = Vector3.MoveTowards(movement, input * moveSpeed, Time.deltaTime * 30); // accelerate at 30 m/s^2
rb.velocity.x = movement.x;
rb.velocity.z = movement.z;
scenic sigil
heady iris
#

Right.

#

This will gradually change your velocity each physics update, rather than just setting it to 5m/s instantly

#

I'm still a bit surprised that you're climbing the wall, though.

I'd also try replacing the capsule with a box collider, just for a sanity check

scenic sigil
#

Last 2 lines give compiler CS1612
Rough translation from Russian: "Failed to change the return value of "Rigidbody.velocity" because it is not a variable."

heady iris
#

oh right, d'oh

#

can't assign individual parts of the velocity

#
movement.y = rb.velocity.y;
rb.velocity = movement;
#

that'll do

scenic sigil
heady iris
#

You want to keep that, since you don't want your current vertical velocity to affect the MoveTowards line

scenic sigil
#

Alright

heady iris
#

Otherwise, it'd "waste" some of your acceleration on moving your Y velocity towards 0

scenic sigil
#

Let me check if this works

#

It slides up slightly but not enough to get on top

#

@heady iris

#

Alright I gotta head out for today

#

Good night (or day), cya tomorrow

waxen socket
#

Hi, what would be the best way to create world space health bars? I can make a world canvas for each of them, but I feel like it's too many canvases. I thought about creating a custom component with LineRenderers, but then I need to updated all positions every frame. Is there any better way?

quaint rock
#

must they be world space

#

could they just be screen space, then do a world to screen space transformation to decide where on the screen to render them

rigid island
# waxen socket Hi, what would be the best way to create world space health bars? I can make a w...

I will show you how you can use only one canvas to draw all your world space UI elements. This method is especially interesting, if you are having performance issues or rendering a massive amount
of elements

Health Bar Image: https://imgur.com/a/J6QRc
Twitter: https://twitter.com/DEEntertainme

▶ Play video
waxen socket
quaint rock
#

its fairly common for stuff like UI over units in a game, or say for effects like coins flying to where on the hud they are displayed etc

heady iris
#

oh my god i can't believe i didn't think of that before

#

i've done one big screen-space canvas

#

although, this does mean that changing anything causes the entire canvas to re-render

#

so I wonder if this is actually better

lament island
#

Quick question (I hope lol) So I have an incoming type and some parameters that I wish to setup an object with. I recognize that I can use activator.CreateInstance in order to do this but I can't seem to pass my delegate parameters into the method because it only takes objects. What is the correct way to do this?

thick terrace
heady iris
#

delegate types are indeed derived from object

knotty sun
lament island
#

Oh I just cast it? Gotcha! I'm storing a type in a serializedObject to setup a subclass for firing

thick terrace
leaden ice
knotty sun
rigid anvil
#

how can i know if a script is physics based or not?

leaden ice
knotty sun
lament island
#

not a delegate type

leaden ice
#

It could mean "using Unity's built-in physics engine". But that's a narrow definition. It could also just mean based on real physical principals.

knotty sun
lament island
#

Thats what I thought but I get an error tryting to convert method group to object

rigid anvil
thick terrace
lament island
#

ohhhhhhhhhhhhh pffft my bad

lament island
#

I thought it was params

thick terrace
#

yeah i think it would just get confusing with the various overloads if it was params sadly

rigid anvil
leaden ice
knotty sun
rigid anvil
leaden ice
#

IIRC Dani's grappling gun game doesn't use Rigidbody

knotty sun
#

sounds like it, mixing physics and non-physics is definitely non trivial

rigid anvil
rigid anvil
leaden ice
#

A grappling gun is inherently physical

#

that means you need to simulate physics one way or another

#

either using Rigidbodies and Uniry's built-in physics

#

or implementing gravity, momentum, forces yourself.

leaden ice
#

it's not that complicated if you do a hybrid setup using Unity's physics engine for collision detection. Basic velocity, momentum, and forces are quite simple.

rigid anvil
#

well ima look a bit more into it and see what i land on, thanks guys

vivid halo
#

I'm making an enemy that shoots a projectile with an arc at the player (or any valid target) and I'm considering whether to use DOTween or just a standard rigid body with physics.

I have both implementations working, but I am wondering if there is any wisdom regarding DOTween: is it generally better to avoid using the additional library if possible, or can it add maintainability value to the code if used properly? Apologies for the vague question

leaden ice
vivid halo
#

I want projectiles to follow various arcs when being fired from enemies toward the player. I can handle this with individual scripts or DOTween, but I'm not sure which would be better long-term.

Sine wave curve, corkscrew curve, standard projectile lob, and other arcs. I heard DOTween might be able to simplify this but I want to gather the thoughts of more experienced devs before I commit to it

leaden ice
indigo verge
#

Is there a good way to teleport an object into a valid position, I.E, if I have two characters overlapping after spawning them, and I just want to snap them out of the invalid position?

silent tapir
#
public static void DropItemIntoSlot(RectTransform slotTransform, RectTransform itemTransform, Vector2 cellSize)
    {
        if (selectedItem != null)
        {
            Vector2 gridOffset = slotTransform.parent.GetComponent<RectTransform>().anchoredPosition;
            Vector2 itemCorner = itemTransform.anchoredPosition;
            Vector2 relativePosition = itemCorner - gridOffset;

            Vector2Int cellCoord = new Vector2Int(
                Mathf.FloorToInt(relativePosition.x / cellSize.x) + Mathf.FloorToInt(gridOffset.x / 100),
                Mathf.FloorToInt(-relativePosition.y / cellSize.y) + Mathf.FloorToInt(gridOffset.y / 100)// Invert Y-axis
            );

            Debug.Log(gridOffset);
            Debug.Log(cellCoord);

            //selectedItem.transform.position = new Vector3(snappedPosition.x, snappedPosition.y, 0);
            selectedItem.image.raycastTarget = true;
            selectedItem = null;
        }
    }```

the grid only responds with the correct cellCoords if the gridOffset is set to 200 for some reason.
vivid halo
# leaden ice The Rigidbody will help you only with parabolic arcs

My instinct is to create scripts by hand like SinewaveTrajectory.cs or CorkscrewTrajectory.cs as physics mods and attach them to projectiles without using DOTween, but I am unsure of which path to take. Is the given information sufficient to recommend an approach?

knotty sun
wide terrace
indigo verge
indigo verge
knotty sun
#

so you want to check an infinite number of points to chose one?

indigo verge
#

I'm basically just asking if there are any existing functions that lend themselves well to this, or if I'll be coding my own implementation.

knotty sun
silent tapir
fleet tide
#

Hey ! what the best way to create an Inventory system in an MMORPG ?

silent tapir
fleet tide
#

Like WOW , a very classic inventory (exept, no backpack or anything, simply an inventory)

silent tapir
#

🏗 @TamaraMakesGames building system video: https://youtu.be/G2w78Xk6UhU
🏞 FREE assets download: https://www.patreon.com/posts/72631393?s=yt
🎁 Support me and DOWNLOAD Unity project: https://www.patreon.com/posts/72632413?s=yt

This tutorial guide will show you how to create a full inventory system with draggable items, bottom toolbar, full inven...

▶ Play video
#

It's most similar to minecraft, I don't play WOW sorry.

fleet tide
#

Okay thanks ! i will check it ^^

silent tapir
full dome
#

Looking for some advice on where to manage object animations.

I have following classes:
Unit - monobehaviour, holds basic information about unit, initializes everything, firing some events
UnitAction - C# class, which performs various unit actions like heal, move etc.
ActionCommand - c# command class for Action that holds action and execution parameters
UnitActionsQueue - monobehaviour that executes queued Commands

Now I am not sure where to put code to manage animations. I will need to react for current executed action and external inputs like damage taken.

My current idea is to create another MonoBehaviour UnitAnimator which references Unit events + UnitActionsQueue and reacts to both sources. Since Actions aren't Monobehaviour on each change of action I'd need to add/remove listeners depending on currently executed action type. I guess it would work but not sure if it's good approach and isn't too complicated.

wide terrace
# silent tapir the 100 is the cellSize my bad.

Ok... I guess I still need more information on what the difference between "correct coordinates" and "incorrect coordinates" are. I'm a little confused by why gridOffset is factored out of itemCorner to get a relative position, then factored back in to cellCoords to produce coordinates which ignore that offset.

Like, if gridOffset is 200, 200 and cellSize is 100, 100, then the very first item on or after the gridOffset position (say it has itemCorner 200, -200/relativePosition 0, 0) has cellCoords 2, 2 instead of 0, 0 - is that correct, and your intended result?

leaden ice
full dome
manic pagoda
#

Any good for coding VS Code themes like this one? For Python it's good for coding but for C# it seems a bit too blinding and not the best

rigid island
#

still haven't found a way to seperate localVars from fields though
(also don't crosspost)

manic pagoda
rigid island
#

also this isn't a unity question

manic pagoda
rigid island
manic pagoda
rigid island
manic pagoda
#

theme does have a relation to coding

#

but anyways

manic pagoda
rigid island
manic pagoda
rigid island
tawny elkBOT
chilly surge
eager yacht
#

I use the defaults since I always forget to make backups of custom themes, so when I reinstall I get sad Kappa

manic pagoda
#

at the end of the day Blender notepad is the best IDE and theme

#

it also got dark mode

spring creek
mellow grail
#

nvm i found it

#

nvm

zinc parrot
#

Real quick before I do a bunch of work and tests on this, is it significantly slower to directly load floats, ints, etc. from a scriptable object every frame vs caching the scriptable objects data into local variables and using those every frame instead?

zinc parrot
#

yeah, cache the scriptable objects and treat it as loading from a class

#

I am wondering if the fact that its a scriptable object introduces much if any overhead

heady iris
#

into local variables and using those every frame instead?

note that fields are not local variables

#

a local variable is a variable you declared inside of a functino

heady iris
zinc parrot
#

ah sweet ok

heady iris
#

In this case, both approaches will load a value from a field

#

so it'll be equivalent

zinc parrot
#

awesome thanks!

rain minnow
#

yeah, i was about to ask if you meant referencing the SO and using its values directly, or caching each value from the SO into a local variable . . .

north rover
#

hello guys how can i make choices and choices like telltale games

heady iris
#

do not attempt to ping user groups

#

imagine pinging 20000+ people because you want to know how to make buttons

#

jesus christ

wide terrace
heady iris
#

you asked "how can i make choices?"

#

without any further information, i can say very very little

spark tinsel
#

I thought I might try read some code today looking for suggestions, have any of you read some c# you think is beautiful?
I'm somewhere between beginner and intermediate

twin jetty
#

Any advice on what to do with this issue? I don't like the jitter that happens with the repeated collision.

leaden ice
#

instead you are likely moving the Transform directly

leaden ice
#

To fix it - start moving your character appropriately with the Rigidbody2D

#

e.g. by setting its velocity

#

I also recommend enabling interpolation on your Rigidbody2D if it is not already enabled.

dusk apex
twin jetty
fleet stratus
#

I tried my best to Load DLL files with c# scripts inside from the streaming assets folder but it didnt work.(Im using it for mod support)

twin jetty
#

I'm now encountering a fun new issue though. I'll figure it out though. I've lost diagonal movement now because I'm using getkeyup to stop the movement.

leaden ice
twin jetty
leaden ice
#

but maybe I don't understand how your movement works

#

sharing your code would be a good start.

#

A typical standard movement script in 2D using velocity might be something like:

Vector2 inputVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
rb.velocity = inputVector * speed;```
twin jetty
# leaden ice sharing your code would be a good start.

This was what I setup with my current knowledge. It's butt ugly though. ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;

// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
     if (Input.GetKey("w"))
    {
        rb.velocity = new Vector3(0, 10, 0);
        Debug.Log("w key was pressed");
    }
    if (Input.GetKeyUp("w"))
    {
        rb.velocity = Vector3.zero;
        Debug.Log("w key was released");
    }

     if (Input.GetKey("a"))
    {
        rb.velocity = new Vector3(-10, 0, 0); 
        Debug.Log("a key was pressed");
    }
    if (Input.GetKeyUp("a"))
    {
        rb.velocity = Vector3.zero;
        Debug.Log("a key was released");
    }

     if (Input.GetKey("s"))
    {
        rb.velocity = new Vector3(0, -10, 0); 
        Debug.Log("s key was pressed");
    }
    if (Input.GetKeyUp("s"))
    {
        rb.velocity = Vector3.zero;
        Debug.Log("s key was released");
    }
     if (Input.GetKey("d"))
    {
        rb.velocity = new Vector3(10, 0, 0);
        Debug.Log("d key was pressed");
    }
    if (Input.GetKeyUp("d"))
    {
        rb.velocity = Vector3.zero;
        Debug.Log("d key was released");
    }

    {
    
    }
    
}

}

leaden ice
#

compare this with the two lines I shared above

dusk apex
#

By default wasd should be accepted

twin jetty
#

Yeah axis is a bit baffling to be at the moment. For now I'll just use the provided code. The docs didn't help my brain to understand it. I'll try to find some videos tommorow.

swift falcon
#

why's it say this

rigid island
tawny elkBOT
swift falcon
#

I tried this and it did nothing ngl

leaden ice
#

your error means you have a duplicate script.

#

but you need to configure your IDE before we can render any further assistance

swift falcon
#

okay thank you

dusk apex
spring creek
# twin jetty Yeah axis is a bit baffling to be at the moment. For now I'll just use the provi...

It mean, it just represents a value. Pressing A would mean GetAxis("Horizontal") returns -1. D would return 1

Then you can make a vector directly from two get axis calls.
For 3d, you would want x to be horizontal and z for vertical

Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;

Then you can just use that directly. A single line for input and plug it into your movement

silent tapir
#
public static void DropItemIntoSlot(RectTransform slotTransform, RectTransform itemTransform, Vector2 cellSize)
{
    if (selectedItem != null)
    {
        // Get the position of the grid (parent of the slot)
        Vector2 gridPosition = slotTransform.parent.GetComponent<RectTransform>().anchoredPosition;

        // Get the position of the item
        Vector2 itemPosition = itemTransform.anchoredPosition;

        // Calculate the relative position of the item to the grid
        Vector2 relativePosition = itemPosition - gridPosition;

        // Calculate the cell coordinates
        Vector2Int cellCoord = new Vector2Int(
            Mathf.FloorToInt(relativePosition.x / cellSize.x),
            Mathf.FloorToInt(-relativePosition.y / cellSize.y)
        );

        Debug.Log("Grid Position: " + gridPosition);
        Debug.Log("Cell Coord: " + cellCoord);

        // Optionally, move the item to the snapped position
        Vector2 snappedPosition = new Vector2(
            cellCoord.x * cellSize.x + gridPosition.x,
            cellCoord.y * cellSize.y + gridPosition.y
        );

        selectedItem.transform.position = new Vector3(snappedPosition.x, snappedPosition.y, 0);
        selectedItem.image.raycastTarget = true;
        selectedItem = null;
    }
}``` **This is the current code I have)
#

It's logging -2, 0 instead of 0, 0. at a 200 grid offset.

cosmic rain
silent tapir
silent tapir
fleet stratus
#

How do I load a dll from a folder at runtime

cosmic rain
silent tapir
#

okay

cosmic rain
fleet stratus
cosmic rain
fleet stratus
#

so I diont remember

cosmic rain
#

Well, try again then and come back with some context and info.

heavy forum
#

Hi, Im trying to make a 2D bomb to destroy tiles, I made this code but is not working, it only destroys a single tile

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

public class BombItem : MonoBehaviour
{
    Tilemap tilemap;
    public float explosionRadius = 1.0f;
    public float timer = 2.4f;

    float destroyedTiles;

    private void Start()
    {
        tilemap = GameObject.Find("Destructible").GetComponent<Tilemap>();
        StartCoroutine(Timer());
    }
    IEnumerator Timer()
    {
        yield return new WaitForSeconds(timer);
        BlowUp();
    }

    private void BlowUp()
    {
        RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, explosionRadius, Vector2.zero);

        foreach (RaycastHit2D hit in hits)
        {

            Tilemap tilemap = hit.collider.GetComponent<Tilemap>();
            if (tilemap == this.tilemap && tilemap != null)
            {
                Vector3Int tilePos = tilemap.WorldToCell(hit.point);

                tilemap.SetTile(tilePos, null);

                destroyedTiles++;
            }
        }
        
        
        Debug.Log("Tiles destroyed: " + destroyedTiles);
        Destroy(gameObject);
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, explosionRadius);
    }
}
fleet stratus
# cosmic rain Well, try again then and come back with some context and info.

@cosmic rain This is my modloader code: ```cs
public class ModLoader : MonoBehaviour {
void Start() {
DirectoryInfo dir = new DirectoryInfo(Application.streamingAssetsPath + "/Mods");
FileInfo[] info = dir.GetFiles("*.dll");

    foreach (FileInfo f in info) {
        Assembly.LoadFile(f.FullName);
    }
}

void Update() {
    
}

}


My compiled c# dll looks like this:```cs
namespace TestLib {
    public class TestScript : MonoBehaviour {
        void Start() {
            Debug.Log("Hello World!");
        }
    }
}

When I run this code I dont know how to attach the dll file to an object to make it run.

leaden ice
heavy forum
#

I tried whith a while loop but nothing

leaden ice
#

It'd be better to just iterate over the tiles in that area

#

A while loop for what

silent tapir
leaden ice
#

That makes no sense

wide terrace
heavy forum
leaden ice
heavy forum
#

idk

leaden ice
#

The problem is - one Collider, one hit

heavy forum
#

so, what can i do?

leaden ice
#

A Physics query is not the answer here

#

Iterate over all the tiles within the radius of the explosion.

#

Find the one in the center with WorldToCell then just iterate over the nearby ones

#

Something along those lines

heavy forum
#

ok, Ill try

leaden ice
#

It's simple addition of coordinates to find the nearby tiles

cosmic rain
fleet stratus
silent tapir
#

no pivots work

cosmic rain
fleet stratus
fleet stratus
# cosmic rain Sure.

how could I rework this code:```cs
foreach(Type type in DLL.GetExportedTypes())
{
var c = Activator.CreateInstance(type);
c.Output(@"Hello");
}


to run the Start() function
cosmic rain
#

Well, think. This is literally an example of how to create an instance and call a function on it.

wide terrace
# silent tapir I've tried everything.

I'm pretty rusty with GUI stuff, but I think it's still something wonky in the pivot/anchor... The math in your last code snippet looks fine to me - the coordinates make sense relative to that 210, 0 gridPosition - but it seems like that might be wrong position to start from. I suspect that you need to start from the coordinates of the left corner (or bottom left? Again, rusty :P), and that 210, 0 might not be it?

fleet stratus
cosmic rain
silent tapir
wide terrace
#

Like this would be functioning perfect if the cells were drawn down and to the right of 210, 0, but they're drawn starting from 0, 0

silent tapir
#

@wide terrace I have tried almost every single anchor and pivot, none of it works

#

you know putting it in the very top left and putting the anchors to a certain number until its close to 0 works. Is this a valid way of doing this?

wide terrace
silent tapir
#

What?

#

well the that would just be what it already is though?

wide terrace
# silent tapir What?

The anchor and pivot can move around within the object. But your cell coordinate space always originates from the top left corner. So instead of setting gridPosition from the rect's anchoredPosition, you need to find a way to ask the rect for the coordinates of it's top left corner, pivots and anchors be damned

silent tapir
#

ah okay

silent tapir
# wide terrace The anchor and pivot can move around within the object. But your cell coordinate...

so I just need to get the top left corner, lets see..

Vector2 anchoredPosition = gridRectTransform.anchoredPosition;

    // Calculate the top-left corner position
    Vector2 size = gridRectTransform.sizeDelta; // sizeDelta gives width and height of the RectTransform
    Vector2 topLeftCorner = anchoredPosition - new Vector2(size.x * gridRectTransform.pivot.x, -size.y * (1 - gridRectTransform.pivot.y));```
#

huh?

wide terrace
#

accidentally hit enter early :)

silent tapir
#

oh lol

#

im not utilizing the topLeftCorner correctly apparently bc it still don't work :/

#
RectTransform grid = slotTransform.parent.GetComponent<RectTransform>();
            Vector2 anchoredPosition = grid.anchoredPosition;

            Vector2 size = grid.sizeDelta;
            Vector2 topLeftCorner = anchoredPosition - new Vector2(size.x * grid.pivot.x, -size.y * (1 - grid.pivot.y));

            Vector2 itemPosition = itemTransform.anchoredPosition;
            Vector2 relativePosition = itemPosition - topLeftCorner;

            Vector2Int cellCoord = new Vector2Int(
                Mathf.FloorToInt(relativePosition.x / cellSize.x),
                Mathf.FloorToInt(-relativePosition.y / cellSize.y)
            );```
#

@wide terrace

wide terrace
# silent tapir <@1097950947369562187>

I think RectTransform has a number of other members which look useful this that might let you skip the math, but maybe like

Vector2 topLeftCorner = grid.GetWorldCorners()[0/* or 1, 2, 3 - not sure which is the top left corner */];

but again - super rusty. Not sure if this is a great choice. Seek a second opinion 👀

silent tapir
#

ill try it

wide terrace
#

It won't work because I substantially misinterpreted that method 😁

silent tapir
#

yeah

silent tapir
#

seems like the other one I had was logical but it still didn't work

wide terrace
# silent tapir so will it still work?

Via some means or another. I don't know the proper way to get the relevant coordinates - I was hoping someone might chime in with the answer cough cough. But I can dig a bit

silent tapir
#

my other method still logs -210,0 bruh

#

use the first slot as the origin of the grid maybe?

wide terrace
wide terrace
silent tapir
#

thats where the "origin" would be

#

I mean could I just get the cellcoords based on the slots? I have access to all of them.

wide terrace
#

Ideally the top left corner again. You could do it from the middle, but I think you might need to change your "floors" to "rounds"? I'm sort of just rambling at this point. I'll brb

silent tapir
#

im so lost 😆

wide terrace
# silent tapir k I ain't sure honestly

This seems functional to me, regardless of anchor positions:

Vector2 topLeftCorner = new Vector2(
  grid.position + grid.rect.xMin,
  grid.position + grid.rect.yMax
);
wide terrace
#

ah my bad. Forgot some xs and ys

silent tapir
#

u mean .x and .y for the grid.position?

#

ah I thought so

wide terrace
#

yeah 😁

silent tapir
#

nw lemme try it out 🙂

silent tapir
#

I really don't understand at this point.

#

I have tried literally everything.

silent tapir
wide terrace
#

yeah

silent tapir
#

can you vc right now?

#

so I can screenshare

wide terrace
#

I can't vc at present, but I'll stare at this a moment longer

silent tapir
#

What should I do next?

#

@wide terrace This is what a guy did on a random wiki:

        Vector2Int cellCoord = Vector2Int.RoundToInt((itemRect.min - gridRect.min) / cellSize);
#

it doesn't work but it worked for him so idk

#

But every time I click it logs (1,0)

#

really weird

#

and (0,0) all the time if it is in the top left

wide terrace
# silent tapir <@1097950947369562187> This is what a guy did on a random wiki: ```cs V...

That seems reasonable... I think it's using the bottom left corners of things for the calcs, and treating 0, 0 as the bottom left cell cord, increasing up and right... I'm not sure why it might go wrong.

I'm afraid to suggest anything else before I play with the UI a bit to get a better handle on it's coordinate system again, lest I lead you further astray with poorly thought out conjecture 😅

silent tapir
#

and ur good

silent tapir
#
            Vector2Int cellCoord = Vector2Int.RoundToInt((itemTransform.GetComponent<RectTransform>().anchoredPosition - grid.rect.min) / cellSize);
#

now its kinda volatile whether it wants to go on the dot, 1 down, or 1 up

#

i will try FloorToInt

#

it works, just gotta fix the y as a -

#

final code:

RectTransform grid = slotTransform.parent.GetComponent<RectTransform>();

            Vector2Int cellCoord = Vector2Int.FloorToInt((itemTransform.GetComponent<RectTransform>().anchoredPosition - grid.rect.min) / cellSize);
            cellCoord = new Vector2Int(cellCoord.x, -cellCoord.y);

            Debug.Log("Cell Coord: " + cellCoord);```
#

it works

wide terrace
stable lintel
#

hi guys

#

i wrote a code for combining several terrains into a single one(just the heights)

#

but the resulting terrain is currently not-colored

#

so i also need a way to transfer terrain textures/layers/splatmap(idk what)

#

and before i do that... How many terrain layers can be on a terrain object?

#

I'm on Unity 6.0 URP

misty blade
#

I'm currently working on a card game where players choose troops and place them on a game grid. I'm having trouble figuring out how to use Unity solutions to achieve this.

I have a Troop class that inherits from ScriptableObject, containing data like its sprite, order in the deck, cost, health, etc. Each troop also has custom functionality: some attack in a straight line, while others attack diagonally.

I created another Troop-like class that inherits from GameObject, where the custom behaviors are implemented. The ScriptableObject Troop has a reference to the GameObject prefab to use the custom logic. This means I have an object with data and another with logic. However, for every data object, there needs to be a prefab with the proper custom script attached, which doesn't seem efficient.

I thought about moving all the custom logic to the ScriptableObject class and passing the Troop placed on the game grid as an argument. But this would require calling methods from the ScriptableObject that are in the GameObject, breaking encapsulation and leading to poor design.

I've never used ScriptableObjects this way before and am wondering how to properly design a system that won't cause problems later in development?

cosmic rain
#

The specific scriptable object could construct that plain C# class instance and provide it to your scene objects.

misty blade
#

Wouldn’t that require an SO to have a reference to a plan C# class? I’m not sure if it’s something that you can assign in editor

cosmic rain
misty blade
#

Yeah I could be done in code. I will try it out and see how it turns out

pine carbon
#

why does this code crash unity?

obj.background.DOColor(falseColor, transitionDuration).onComplete += () => {
    Executor.Instance.DoLater(() => {
        HideUI();
        onCompleted?.Invoke(false);

        CountdownManager.Instance.Continue();
        obj.background.color = defaultColor;
    }, 0.3f);
};
public static Tweener DOColor(this Image img, Color targetColor, float duration) {
    return DOTween.To(
        () => img.color.ToVector(),
        (val) => img.color = val.ToColor(),
        targetColor.ToVector(),
        duration
    ).Play();
}
somber nacelle
#

are you sure it is that code and not perhaps whatever is subscribed to your onCompleted event

pine carbon
#

QuestionManager.Instance.NextQuestion((bol) => MissionManager.Instance.NextMission());

#

this is how i call it

#

hold on

#
public void Choose(int index) {
    if (currentQuestion == -1) return;
    TextObject obj = answerObjects[index];
    Color defaultColor = obj.background.color;
    int answer = questions[currentQuestion].answer;
    if (lessQuestions) {
        index = index <= 1 ? 0 : 1;
    }
    bool win = index == answer;
    if (win) {
        obj.background.DOColor(trueColor, transitionDuration).onComplete += () => {
            Executor.Instance.DoLater(() => {
                obj.background.color = defaultColor;
                CountdownManager.Instance.Continue();
                onCompleted?.Invoke(true);
                HideUI();
            }, 0.3f);
        };
        return;
    }
    obj.background.DOColor(falseColor, transitionDuration).onComplete += () => {
        Executor.Instance.DoLater(() => {
            HideUI();
            onCompleted?.Invoke(false);

            CountdownManager.Instance.Continue();
            obj.background.color = defaultColor;
        }, 0.3f);
    };
}
pine carbon
#

the weird part is

#

it doesnt crash inside the if(win)

#

it becomes red and the game crashes

somber nacelle
#

attach the debugger and break all when it starts the infinite loop. you'll be able to inspect what the main thread is doing and find the actual culprit

pine carbon
#

okey

pine carbon
#

idk why but when i changed the order of HideUI() onCompletedInvoke etc. it worked

glacial yacht
#

I am having problems with animations with a wolf asset i downloaded (already rigged and animated) and just copied most of the componentes from the characeter from the third person controller series.
The problem is that it seems to be stuck
The animation doesnt seem to be playing because the blend tree just causes it to change between the start of each individual animation.

#

Screen recording of my issue.
(No audio)

trim rivet
#

How do I get the cursor to hide in 'Play Maximized' in 2022 ? anyone know ?

Cursor.Hide does not do anything.

main shuttle
frank marsh
#

Hello, i would like to be able to change the dynamic friction of a specific rigidbody at runtime, and i dont see how to do it without modifying the physic material assigned to the rigidbody. It seems that unity wont allow the creation of phyisic material at runtime (i thought about creating one of them for each rigidbody with a "new"). Does someone has an idea about how i could do that without creating a large pool of physic material in the scene that i would assign and modify in script?

molten venture
#

Is there a way to find which instance Invoked a certain Action from the function that was subscribed to it?

#

So, if I do:

myObject.myAction += myFunction;

Can I find from the body of myFunction the object that invoked myAction? (in this example, myObject)

#

I ended up adding myObject as a parameter to the action:

myAction.Invoke(..., myObject);
vague rock
#

Hello guys! Not directly a code question, but I'll be implementing a genetic algorithm for my enemy (a pirate ship) and I was thinking which parameters it could have

#

I though maybe player distance and direction (related to front face), along side the enemy and player health

#

although I don't how I'd express this as keys in a dictionary (the keys are the genes)

#

maybe ranges?

#

Does someone have suggestions?

simple ruin
#

Anyone have a clue as to why the hitbox is way off from the visualizer?

#

visualizer is the thicker box

vague rock
#

shouldn't boxCollider.center already be the center? (idk tbf, just thinking)

simple ruin
#

p sure box collider center is the offset from the object

#

so a box collider has a hidden transform.position, rotation, and scale, and two more fields for scale and center

simple ruin
#

i was told gizmos dont work in runtime when built

steady moat
#

I see, just wanted to be sure you were aware.

simple ruin
#

actually tbh

#

gizmos is not a bad idea

#

i can check to see if my hitbox code is correct

#

I think I partially found the culprit

#

center is inversely affected by scale

#

that's actually pretty funny I won't lie

vague rock
#

why?!

#

that makes no sense

simple ruin
#

blame unity

#

heh

#

yeah hmmmm

#

getting closer.. I guess?

vague rock
#

something random: why does Mathf.Ceil return a float?

heady iris
#

there's CeilToInt if you want an integer

simple ruin
#

the f in Mathf

heady iris
#

you may still want to floor or ceiling a number and then continue to use it as a float

vague rock
heady iris
vague rock
#

so it need's to be Mathf (that was my thinking)

heady iris
#

ceil(4.5) is 5. It doesn't matter that 5 happens to be a float here

vague rock
#

although just now I thought that the f was for float

heady iris
#

it is indeed short for "float"

#

System.Math is all double-based

vague rock
#

I always though why unity's math library was called Mathf and not Math

#

lol

heady iris
#

UnityEngine.Mathf provides the same operations, but with floats

scenic sigil
#

5 = int
5.0 = double
5.0f = float
5.9 = double
5.9f = float

vague rock
#

makes sense!

#

thx

heady iris
#

1.23m = decimal

#

secret bonus type

vague rock
#

lol

#

it's "infinite" precision?

scenic sigil
#

not infinite

#

but a lot

#

honorable mention: BigInt

heady iris
#

The funny part is that it's a decimal floating point number

#

rather than a binary floating point number

#

so it can exactly represents things like 0.01

#

(i have never used it)

#

i want to say it's mostly there for finance applications

scenic sigil
heady iris
#

but I'd prefer to use a fixed-point number in that situation

scenic sigil
#

btw

#

Hey, how do I make my Rigidbody character stay on my moving platform? The platform has a kinematic Rigidbody and a Box Collider, here is the code:

using System.Collections;
using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
public class MovingPlatform : MonoBehaviour
{
    [SerializeField] private Vector3 start;
    [SerializeField] private Vector3 end;
    [SerializeField][Range(1f, 20f)] private float timeToMove = 2f;
    [SerializeField][Range(0, 5)] private int delayAfterArriving = 1;
    [SerializeField] private bool paused = false;

    private bool moving = false;
    private bool reverse = false;

    // Start is called before the first frame update
    void Start()
    {
        transform.position = start;
    }

    private void Update()
    {
        if (!moving && !paused)
        {
            StartCoroutine(MoveToPosition());
        }
    }

    private IEnumerator MoveToPosition()
    {
        moving = true;
        Vector3 currentPos = transform.position;
        float t = 0f;
        while (t <= 1f)
        {
            while (paused)
                yield return new WaitForSeconds(0.1f);
            t += Time.deltaTime / timeToMove;
            transform.position = Vector3.Lerp(currentPos, !reverse ? end : start, t);
            yield return null;
        }
        transform.position = reverse ? start : end;
        reverse = !reverse;
        yield return new WaitForSeconds(delayAfterArriving);
        moving = false;
    }
}
plucky inlet
#

Oh, you are teleporting the platform? either switch to rigidbody then or calculate the velocity

scenic sigil
scenic sigil
plucky inlet
#

Why do you even use a rigidbody on the platform then?

scenic sigil
plucky inlet
scenic sigil
plucky inlet
#

Why? You have a rigidbody and want to attach its movement to your players movement, so the platform does not slip away while your character is stationary, right?

scenic sigil
#

Yeah, I want the character to go with the platform

plucky inlet
#

So either you need the velocity, which does not work when you use transform.position, or you have to move your player the normal movement + the movement of the platform calculated

scenic sigil
#

...?

#

Go ahead

#

Put it right after the backticks, not on a new line

plucky inlet
#

Maybe put it in a link on hastebin or whatever is suggested here? 🙂

scenic sigil
#

This part is pretty okay, though I'd add a [RequireComponent(typeof(SpriteRenderer))] before public class Enemy so that the SpriteRenderer is automatically added with this script

plucky inlet
#

What is your question about your script tho? like second opinion about what exactly?

plucky inlet
scenic sigil
#

Like, what exactly do I need to do to keep the player on

plucky inlet
# scenic sigil Like, what exactly do I need to do to keep the player on

I could just rewrite what I wrote there 😄 So what part is not clear? Basically, you have a second movement input when standing on a platform. That needs to be taken into account. Easiest would be to add the velocity, if you would switch over to move it with rigidbody instead of transform. But if you dont want to do that, you might need to move your player towards the platform positoin, which is updating constantly. Not sure, how smooth this could go, thats why I suggested using rigidbody for your platform

scenic sigil
plucky inlet
#

So there are things in the general setup, that could be simplified, but not about the code itself. Instead of letting every enemy calculate its own distance in update, you could use the player and overlapsphere (if using physics) to detect enemies in range and then call them to shoot. That way, only one update would check instead of every enemy.

plucky inlet
scenic sigil
plucky inlet
#

I mean the snippet in the first answer, not the thread owners script 🙂

scenic sigil
#

And, what is inverseMoveTime?

plucky inlet
#

just a speed value

#

multiplier for deltatime to speed or slowdown

scenic sigil
#

Does it like accelerate?

plucky inlet
#

Time.deltaTime is time between frames. so if you move from point A to B with a percentage of 0.1(Time.deltaTime for example), it will move 10% of the distance. And then next frame it moves again 10% and so on. If you set the multiplier to 2, it ould go 20% per frame and so on

scenic sigil
simple ruin
plucky inlet
simple ruin
#

LMFAO

scenic sigil
plucky inlet
# simple ruin

How many spots can you give yourself to error out 😄

scenic sigil
vague rock
# simple ruin

now publish and sell in the asset store for 100 dollars to pay the effort \j

simple ruin
#

i was using print statements to test why the box collider was drawing wrong and I was like "why the fuck am I getting the same series of messages 6 times"

simple ruin
scenic sigil
plucky inlet
#

Smooth is subjective, just play around with your values

scenic sigil
#

Okay

#

But first I gotta integrate the answer's logic into my code

plucky inlet
simple ruin
scenic sigil
#

With all my fins and flips (I have no idea what that idiom is exactly)

simple ruin
#

i dont really see a way to fix that because its coded to onValueChanged LMAO

plucky inlet
simple ruin
scenic sigil
simple ruin
#

like, I have 6 scripts controlling the UI right

#

each script has 1-2 near carbon copy populate dropdown, load input field, add, and deletion scripts, among others

#

i looked at it and said

#

"yeah, I could probably use a lambda"

#

"but copy pasting is faster"

plucky inlet
#

but then you looked at it and said "if it works, it works" 😄

simple ruin
#

until I started running into the bugs that consumed 2 days of my life

plucky inlet
#

Karma? 😉

simple ruin
#

lmfao true

#

honestly for my first unity project this thing has taught me more about what NOT to do than what TO do

#

dont be lazy and copy paste code, practice good encapsulation, and dont go ham with data structures

#

i have a list with a queue of deleted indices and a second list mapping indices to post-deletion indices for the sole purpose of keeping the primary list's elements position stable after deletion when I could have just used a hash table

#

why? I don't fucking know. I thought I was being smart but it was a fucking nightmare

scenic sigil
#

@plucky inlet Uhh the snippet in the answer is problematic... MovePosition only accepts 1 argument and has no overloads

public IEnumerator SmoothMovement(Vector2 end)
{   
    yield return new WaitForFixedUpdate();

    rb.isKinematic = true;

    // If you really need a precision down to epsilon
    //while (!Mathf.Approximately(Vector2.Distance(rb.position, end), 0f))
    // otherwise for most use cases in physics the default precision of 
    // 0.00001f should actually be enough
    while(rb.position != end)
    {
        rb.MovePosition(rb.position, end, inverseMoveTime * Time.deltaTime); // ???

        yield return new WaitForFixedUpdate();
    }

    rb.position = end;
    rb.isKinematic = false;
}
vague rock
dense zenith
#

what does this mean? how do i fix it?

vague rock
#

some object is null

gentle pawn
vague rock
#

you need to see if you're actually setting it up

vale wharf
#

I don't think they're doing anything wrong. Look at where the error is coming from. It's coming from Unity's own code.

grizzled bough
#

guys i am trying to make camera movement like in cluster truck where the camera bobs down how do i do it , i triyed mutiple times but i couldn't get it, somebody please help me notlikethis

vague rock
knotty sun
vale wharf
#

Writing a pretty complex character controller that utilizes the animator's built-in statemachine to handle the multiple different states.

Issue I'm having right now is that states can't really communicate with eachother (this seems to be a limitation of the animator's state machine?). The way I've solved this currently is by having each state reference the owner (the base player controller) and I've ended up having to add extra variables which are solely for trasmitting data between states.

This feels a bit ugly and hacky. The player controller class only handles applying forces to the rigidbody based on a movementVector, which is modified by states. Having it store variables that are solely for the states feels ugly.

#

It's difficult for me to talk in-depth about how everything is setup without basically doing a write-up of my entire codebase.

#

I could use animator parameters for communication, but a lot of this communication uses vectors, which aren't a supported parameter type

#

I could split the vectors into 3 float parameters, but that seems like it would get out of hand quickly

plucky inlet
#

And why not store the values on your character and. just let the state do its state thing and the controller handle the variables?

vale wharf
#

there's 9 states (one not pictured sinced it's not implemented yet). They're updated as long as the animation the state is a part of is updated

#

States and their behaviour are tightly coupled with the animations, which is why I'm using the animator state machine for this.

vale wharf
#

I think having a dedicated component called StateData might be better.

heady iris
#

shaders don't "appear"

#

you can certainly enable or disable a renderer

#

i'm not sure why you'd want to condition that on the existence of a GameObject, rather than just having a component with a bool field on it

quaint rock
#

am assuming they got something like a version of a shader for when things are wet or something similar

#

personally i would handle that with a global shader float to blend in and out that effect and a global shader keyword to disable it fully as needed

heady iris
#

yeah

indigo verge
#

Are there any existing tools to turn a closed Unity Spline into a concave polygon?

leaden ice
indigo verge
#

As far as I understand, what I'm trying to do is sample a spline to create an outline of points, then take that outline and earclip it to create a polygon filled with triangles

#

I was just asking if there was already a resource for that, or if I was going to need to do it myself.

rigid island
#

ohh so fill the inside area within spline area

#

you already have the points just draw the mesh

heady iris
#

that's non-trivial

leaden ice
#

with the points

heady iris
indigo verge
indigo verge
#

That is fascinating. Thank you, I'll try that out!

#

I'll be back if I need more help.

exotic tartan
stable lintel
twin jetty
#
    {
      Vector2 inputVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
      rb.velocity = inputVector * speed; 

      if (Input.GetKeyDown("left shift"))
      {
        speed = speed + 1;
        StartCoroutine(subtractEnergy());
      }
      
      if (Input.GetKeyUp("left shift"))
      {
        speed = speed - 1;
        StopCoroutine(subtractEnergy());
      }
    }
              IEnumerator subtractEnergy()
        {
            for(;;)
            {
            energy = energy - 1;
            yield return new WaitForSeconds(1f);
            }
        
        }  ```
Any clue why this coroutine doesn't stop?
indigo verge
knotty sun
twin jetty
knotty sun
tawny elkBOT
twin jetty
knotty sun
#

It's not that difficult

Coroutine cor = null;
void Update()
    {
      Vector2 inputVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
      rb.velocity = inputVector * speed; 

      if (Input.GetKeyDown("left shift"))
      {
        speed = speed + 1;
        cor = StartCoroutine(subtractEnergy());
      }
      
      if (Input.GetKeyUp("left shift"))
      {
        speed = speed - 1;
        if (cor != null) {
           StopCoroutine(cor);
           cor = null;
        }
      }
    }

Just requires a little application of syntax and logic

spring creek
twin jetty
knotty sun
spring creek
#

Setting it back to null will tell you that it is not running

heady iris
#

Coroutine is like a ticket. You get one when you ask Unity to start a coroutine.

#

You can give Unity the Coroutine and tell it to stop running that specific coroutine.

#

I believe it's fine to call StopCoroutine with a null argument (and it definitely is to pass it a Coroutine that has already finished running)

#

In many cases, though, flinging null into a function that expects an actual reference will cause an error.

knotty sun
#

best practice

heady iris
#

It's also more semantically correct

#

If a coroutine is executing, stop it

knotty sun
twin jetty
heady iris
#

show your new code

#

we can't guess what you wrote

#

!code

tawny elkBOT
twin jetty
knotty sun
heady iris
twin jetty
# knotty sun tbh I fail to understand how you can NOT understand the code, it's extemely simp...
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody2D rb;
    public int speed = 3;
    public int energy = 100;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        
    }

    // Update is called once per frame
    Coroutine cor = null;
    void Update()
    {
      Vector2 inputVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
      rb.velocity = inputVector * speed; 

      if (Input.GetKeyDown("left shift"))
      {
        speed = speed + 1;
        StartCoroutine(subtractEnergy());
      }
      
      if (Input.GetKeyUp("left shift"))
      {
        speed = speed - 1;
        if (cor != null) {
           StopCoroutine(cor);
           cor = null;
          
      }
    }
              IEnumerator subtractEnergy()
        {
            for(;;)
            {
            energy = energy - 1;
            Debug.Log("Loop continues");
            yield return new WaitForSeconds(1f);
            }
        
        }   
}
}
heady iris
#
        StartCoroutine(subtractEnergy());
#

I am unsure on how this is exactly the same.

twin jetty
#

Ok, I missed a small section. I apolgize. No need to be an ass about it though

heady iris
#

we hear "it was exactly the same code" a lot

#

it rarely is

wide terrace
#

I think the brackets are misaligned as well - it looks like the coroutine might be getting defined within Update()

knotty sun
heady iris
#

That part is fine.

twin jetty
wide terrace
twin jetty
topaz charm
#

I think that was quite uncalled for, please maintain a civil tone at all times 🙂

knotty sun
#

lets look back at the conversation
Coroutine cor = StartCoroutine()
cor = StartCoroutine(subtractEnergy());
And it's my fault?

topaz charm
#

It's good that everyone is trying to help, but if you feel like you are getting frustrated with someone's learning curve, maybe you aren't the right person to help

#

Please move on now though 🙂

heady iris
#

Do you now understand what the problem is?

twin jetty
#

Thanks for your help as well Fen!

vale wharf
#

Kind of a weird question, How can I calculate how high a rigidbody will go when given a vertical impulse force? Furthermore, lets say I apply a vertical impulse force to a rigidbody and then press a button at a specific point in the rigidbodies trajectory, how can I determine what point along it's trajectory the rigidbody was when the button was pressed?

#

the point along it's trajectory should be a normalized value too (i.e. 0-1 where 0 is start of trajectory, 1 is end of trajectory, and 0.5 is the middle of the trajectory)

vestal arch
#

well, given the object's mass and gravitational acceleration, it's a pretty straightforward physics formula

#

v^2 = u^2 + 2as, J = mu
s = (J/m)^2/2g
i believe that should be it

lean sail
leaden ice
#

Is that when the body returns to the height it was launched from?
Is it when it collides with something in the scene?

heady iris
#

If you assume it's going to hit the ground at the same elevation it started at, it's actually extremely simple

#
Mathf.InverseLerp(verticalSpeed, -verticalSpeed, rb.velocity.y);

where verticalSpeed is the starting vertical speed

#

The acceleration due to gravity is constant.

#

To calculate verticalSpeed from an impulse, you need to combine:

  • the original y velocity
  • the added y velocity from the impulse
#

An impulse of magnitude 1 changes your momentum by 1

#

Momentum is mass times velocity

vale wharf
#

I suppose end of trajectory in my case would be the peak height it reaches

heady iris
#

Divide the impulse's magnitude by the mass to get the change in velocity

#

so

var delta = impulse / rb.mass;
float startSpeed = rb.velocity.y + delta.y;
heady iris
#

note that this does not account for drag

lean sail
vale wharf
#

Use case is for a 'hover' state in my character controller. When player holds space after jumping, they start to hover (this will only happen if the player is not on the ground becase they jumped, not because they fell off a ledge or whatever). When they started hovering (i.e. at the peak of the jump trajectory) influences how long they hover

runic pawn
#

so I have a vertical layout group which contains PlayerRow's of a few UI items. I want the entire row to be clickable like a button, so I put a Button component on my PlayerRow and used the Image of the row as the Target Graphic for the Button... It basically works but the problem is that i have to click several pixels below the visible row to hit the button, how can i make it so that I can click on the correct spot to click the button?

#

I have to click below the button in that area to hit the button, but it should work by clicking the Player One row instead..

#

okay, so if i set the image on the PlayerRow to Native Size, then it works... but would prefer not having to do that...

heady iris
lean sail
quasi edge
#

I have a velocity Vector on the player. I need the player to rotate to look in the direction of it's velocity. Anyone know how to do this?

#

I am little confused with using quaternions vs vector3s

quaint rock
#

can also use Quaternion.LookRotation(velocity) if you want to create a rotation facing in the direction of velocity so you can slerp to it or if you need to combine with other rotations

rose rover
#

So I'm trying to make an enemy what dies when it's health reaches 0 but my destroy function just refuses to work, does anyone know what I need to do?

tawny elkBOT
rigid island
#

doesn't work cause you got syntax error

rose rover
#

whats the error? I'm really new so I don't know stuff like that yet

simple egret
#

Line 25 indeed contains invalid code, and should be underlined red

#

Follow the instructions above to set up Visual Studio, so you get the errors highlighted directly in the code

foggy iron
#

Hi guys, on my Unity project, I get some problems, when I walk with my playercharacter, when I force walking in front of a wall I pass throught it, why ?

This is The part of my code where I made the playercontroller :

`public float speed = 5f;

void Update()
{
if (!assemblerManager.isPlayerFrozen && !ComputerInteraction.isPlayerFrozenByComputer)
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical) * speed * Time.deltaTime;
        transform.Translate(movement);
    }

}`

#

On left the wall and on right the player

hexed pecan
foggy iron
#

oh okk !

hexed pecan
#

So rigidbody.AddForce or rigidbody.velocity for example

foggy iron
#

okk thanks a lot guy really !

golden lichen
simple egret
#

Not the right channel for this I'm afraid

prisma birch
#

Anyone know why my Visual Studio stopped showing the Alt+Enter option autocomplete/replace code with suggestions here? Just stopped showing up today. Have the package installed and VS is up to date.

golden lichen
#

it's a coding tutorial, so why not?

simple egret
#

This channel is more for questions directly

golden lichen
#

it says I don't have access to that link

simple egret
#

Oh my bad it's in a locked session, not sure why Discord allowed me to post this here

simple egret
golden lichen
prisma birch
silent tapir
#
public static void DropItemIntoSlot(RectTransform slotTransform, RectTransform itemTransform, Vector2 cellSize)
    {
        if (selectedItem != null)
        {
            RectTransform grid = slotTransform.parent.GetComponent<RectTransform>();
            Vector2 itemAnchoredPosition = itemTransform.anchoredPosition;
            Vector2 gridMax = grid.rect.max; // Use max since top-right alignment

            Vector2Int cellCoord = new Vector2Int(
                Mathf.FloorToInt((gridMax.x - itemAnchoredPosition.x) / cellSize.x),
                Mathf.FloorToInt((gridMax.y - itemAnchoredPosition.y) / cellSize.y)
            );

            Debug.Log(cellCoord);

            Vector2 snappedPosition = new Vector2(
                -cellCoord.x * cellSize.x - slotTransform.parent.GetComponent<GridLayoutGroup>().spacing.x * cellCoord.x,
                -cellCoord.y * cellSize.y - slotTransform.parent.GetComponent<GridLayoutGroup>().spacing.y * cellCoord.y
            );

            selectedItem.GetComponent<RectTransform>().anchoredPosition = snappedPosition;
            selectedItem.GetComponent<Image>().raycastTarget = true;
            selectedItem = null;
        }
    }``` so this system works great when I have the topLeft anchor and pivot for everything but now that I move it to the top right anchor and pivot for everything. The slot that should be 0,0 is 4,0. It's inverted.
#

How can I get it to 0,0?

strange gust
#

i have encountered an issue regarding a pretty hastely put together enemy spawner for a little game i am trying to make, the issue is that my coroutine seems to run a small part of the code inside of it twice without upping the iteration counter nor the coroutines counter while still changing some values which causes an error

https://gdl.space/ubayomalur.cs
this is the script for the enemyspawner

heady iris
#

Notice how the second one has a WaveCount of 0

#

yet it claims to be on day 0, just like the first one

strange gust
#

It could be the case, let me check rq

#

Well damn it appears to be that, thanks. I made two objects, one called "DayManager" and the other "EnemyManager" and just seemed to forget about it

strange gust
heady iris
#

no prob!

#

By the way, a handy way to spot this is to add a second argument to Debug.Log

#

You can add a "context" object (any Unity object, like a GameObject, a Material, etc.)

#

clicking on the log entry will take you to the context object, if it still exists

strange gust
#

Yeah i used that before on another thing, but i didnt realize this couldve been the case on this thing, but maybe its good practise to just use context on debug.logs standard

stable quest
#

Hey folks! Here's a fun question. For inconvenient reasons (let's not get into it), I need to instantiate a clone of a static object in a new location. Naturally Unity does not want to do this, since it requires moving a static object. Is there any way to force it to do this anyway?

#

So far I've tried:

  • setting the static flags of the clone to false, then moving it
  • setting the static flags of the original object to false, then cloning it, then moving the clone
  • setting the static flags of the original object to false, then instantiating the clone already at the position i want it
    None of these have worked so far.
rigid island
#

why not just make a prefab out of the object and spawn that in ? why clone the static?
the static object becomes part of a larger mesh

stable quest
#

Yeah, that's impractical for workflow reasons unfortunately

rigid island
#

not much can be done there ig

stable quest
#

I'm thinking if I can force the object to never be batching static that might work

#

all it really needs is to be lightmap static

cosmic rain
#

I know what a command pattern is. But depending on how exactly you want to use it, the response would be vastly different.

From your example, it seems like you want the commands to interact with the unity API. In this case the answer is simple: you can't call most unity API from background threads, and even more so from jobs. Unity will throw an error if you try to do so.

exotic quest
#

As everyone know when unity loads a scene (for me) the game and editor freeze for seconds, id there any ways to remove that freeze? Like in hollow knight, seamless load if you want

swift falcon
#

What will happen if you put a reference type in a struct? Assume that the **struct **is stored in the heap.
• Will it give you copy of the value and it wont overwrite even you changed something of the value? // It will give you it's memory address
• What will happen if you overwrite reference type inner values? // Since you have it's memory address, it will change inner values of the class
• What happens if you put a delegate in struct and take from struct? Will it copy or give you it's address? // Delegates are immutable. If you try to change their inner value via +=, then you create new instance which means you cannot change anything important of a delegate.
First tests: https://dotnetfiddle.net/DMH8Ta

rigid island
exotic quest
#

Even with async its freezes, or maybe it doesnt work in editor?

rigid island
exotic quest
#

I have to show my script?

vestal cipher
#

anyone know why this doesnt play my audio every 30-90 seconds?

swift falcon
#

Hey hey look closely: you are decreasing the time count down but not checking if the countDown hit zero or less.

#

I have a coffee for you next to me. Maybe you should go outside for a while like i will do now.

vestal cipher
#

thanks foir the help tho

#

dunno how i didnt see that lol

vale wharf
#

Trying to code the "hover" state for my character controller. When player holds space while in air after jumping, the player should start to hover.

I want the motion of the hover to be physics and procedural. Basically, it should modulate vertically along a sine wave that slowly fades out the longer the player hovers. As the sine wave fades out, gravity pulls the character more until they hit the ground.

#

This should be a force applied to the rigidbodies Y velocity

#

not entirely sure how to achieve this, however. Obviously I know what a sine wave is and how to make one, but I don't know how to specifically get the behaviour I just described.

leaden ice
#

A PID controller that isn't tuned properly will overshoot and correct itself resulting in a wave like this

#

So you can intentionally tune it this way

vale wharf
#

Wouldn't that only really work if I had a specific height the player should be hoverng at? The hovering motion I'm envisioning is essentially like a paper bag under a fan (see animation) or a piece of paper fluttering through the air

leaden ice
#

It's all very tunable

lean sail
#

very very few people are gonna come tutor you for free. Just post your question

keen raptor
#

Hey guys, I was wondering if someone can help me look for any improvements that I can make to the code for my player movement script. Since this script depends the player states, I already know that it would be ideal to have a state machine using abstraction instead of using enums. Are there any other advices?
Here is the entire code: https://gdl.space/ajefesulab.cs

#

for example, is it a good idea to run a switch statement in the fixedupdate the way I did it?

dusk apex
#

Tip: avoid premature optimization and use the profiler if there are critical concerns

keen raptor
#

what do you mean?

cosmic rain
#

Basically, if it works, don't touch it.

#

Though, I'd say that you should probably avoid using public fields.

dusk apex
cosmic rain
#

The only thing that stands out is the use of public fields. That should be refactored to serialized private fields and properties if public access is needed.

keen raptor
#

there is one thing in the code that does not work however. So basically, I have been trying to detect a side switch (meaning detecting if the player went from left to right and vice versa), but the condition does not always return true when I am switching sides. Here, ill summarize the code so that you don't have to look at for it:

    void update{
        PreviousMovementDirection = CurrentMovementDirection;
        if (Input.GetKeyDown(KeyCode.A)) CurrentMovementDirection = -1;
        else if (Input.GetKeyDown(KeyCode.D)) CurrentMovementDirection = 1; 
        EnabledSideSwitch();
    }
    private void EnabledSideSwitch(){ //I use hasSwitchedSides variable as the value that determins when the side switch occures which is used in multiple part in the 
        if(PreviousMovementDirection != CurrentMovementDirection) hasSwitchedSides = true; 
        else hasSwitchedSides = false;
    }

what could be the issue here?

dusk apex
#

Where do you call enable side switch?

#

Also, nothing is returned so I'm assuming you're referring to the value of has switched sides never being true

keen raptor
keen raptor
cosmic rain
dusk apex
#

Assuming you can only be facing left or right, you probably could get away with simply a boolcs private bool facingRight; public bool FacingRight { get => facingRight; set { if(value != facingRight) faceHasChanged(); facingRight = value; } }

keen raptor
keen raptor
cosmic rain
keen raptor
#

yes

cosmic rain
#

Gonna take a while to load it on my phone...

cosmic rain
keen raptor
dusk apex
cosmic rain
#

Ah, nvm, found one

dusk apex
#

Instead of creating fields and getters/setters for everything, you can just opt to use properties.

cosmic rain
#

Debugging code is simple:
Something doesn't happen? What are the conditions for it to happen? Where is it called from? Are the conditions satisfied when you expect them to be satisfied? Are they satisfied when the code is called? If not, then where are they satisfied? When do the relevant variables change? Are they changing properly? Are they resetting to a different value before the condition is checked?

It's all simple logic. And you can use debug logs or breakpoints to confirm all this things. Don't work harder. Work smarter.

shell scarab
#

Would unity be causing me to get this error? All the sourceNames use nameof(method), and all the methods are private statics in the same class that return IEnumerable<T>s (where T is some type like uint) as the ValueSource attribute. Also, why is it looking for a dll in that location??

keen raptor
#

so I think the problem here is that this value changes too quick for the values to return "-1 1"

#

maybe changing the condiotion to a better one might fix the issue, but I can't really think of any 😅

cosmic rain
keen raptor
# cosmic rain What do you mean by "too quick"? Break it down. Then confirm the assumption. The...

Here ill break it down. So the update function is running each frame, and when there is a change in the current value, the previous value will change with it but not immediately. So we make an if statement that checks if there is a change or not. Now, just for some testing purposes, I made and if statement that checks if there is a change in the values, it would print out a message, which it did on every turn. But if I place a function with that same if statement and sets a value to true when there is a change, it does not always detect that change. Why??

#

maybe using Dalphat's code might fix this issue?

//Dalphat's code
private bool facingRight;
public bool FacingRight 
{
    get => facingRight;
    set
    {
        if(value != facingRight)
            faceHasChanged();
        facingRight = value;
    }
}
full canopy
#

how do i get oncollisionenter working for an object that has a rigidbody in the root and all colliders in children? as far as i can tell a script only gets a call to oncollisionenter if the rigidbody and colliders are on the same gameobject. checking from the children where the colliders are yields no results, and checking from the parent with the rigidbody only also gives nothing. it only works if i have a rigidbody on the same object as the collider

#

wait i may be dumb

#

yeah i edited a prefab thinking it would change the thing but i forgot i unpacked it facepalm
though looks like unfortunately it still only registers that on the rigidbody object, not the collider object

cosmic rain
autumn field
#

I feel like I'm going insane. Is there any reason this shouldn't work?
All the variables look correct, but lerping the audio source volume does nothing.

// called every frame
_slideAudioSource.volume = Mathf.Lerp
(
    _slideAudioSource.Source.volume,
    _slideTargetVolume,
    1f - Mathf.Exp(SlideResponse * deltaTime)
);
shell scarab
#

Well that Lerp function is being used wrong for one. But, 1 - Mathf.Exp(20 * deltaTime) is going to pretty much the same number every frame since you're doing Mathf.Exp(20 * ~0.0045)

#

I think you actually want something like Mathf.SmoothDamp

autumn field
#

I use exp lerp everywhere and it works, its just a more responsive version of the traditional lerp damping.

 ```cs
public class VolumeTest : MonoBehaviour
{
    public AudioSource source;
    private bool flag;
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        flag = true;
        
        if (flag)
            source.volume = Mathf.Lerp(source.volume, 0f, Time.deltaTime * 0.5f);
    }
}
```~~~
#

Ah Im missing a negative i think

shell scarab
autumn field
#

This is a very common technique I promise

shell scarab
#

and I promise you, it's wrong to do it like that, because lerping interpolates between x and y, so if you lerp between CURRENT and TARGET by a delta time, you'll move a slight % of the distance between CURRENT and TARGET every frame, and then the next frame CURRENT is different, so you never actually reach TARGET.

wide terrace
autumn field
autumn field
shell scarab
#

It's not proper use of it, but if you're aware of that and don't care then go ahead :)

autumn field
#

I am aware it is not *perfectly consistent perfect depending on framerate

shell scarab
#

thats not what I mean, I mean that you don't ever reach your target.

#

Anyways, how does 1f - Mathf.Exp(SlideResponse * deltaTime) work? it seems to me it should just do 1 - Mathf.Exp(20 * ~0.045), but it works as a lerp for you?

cosmic rain
autumn field
# shell scarab thats not what I mean, I mean that you don't ever reach your target.

you don't ever reach your target
Yes I know. It's fine 👍, it will get very very close very quickly to the point that it might as well be 0 for use-case.

@cosmic rain Yea I was missing a negative. It is working now with -SlideResponse

slideSoundSource.Source.volume = Mathf.Lerp
(
    slideSoundSource.Source.volume,
    _slideTargetVolume,
    1f - Mathf.Exp(-SlideResponse * deltaTime)
);
                
cosmic rain
#

I don't see a debug log here

shell scarab
#

dilch they said it works why would they provide a debug log, how would they

cosmic rain
#

But if you got it working, the issue is solved I guess

autumn field
#

Here's the debug.log 😛

Debug.Log($"Volume: {slideSoundSource.Source.volume}, Target: {_slideTargetVolume}, New: {Mathf.Lerp(slideSoundSource.Source.volume, _slideTargetVolume, 1f - Mathf.Exp(SlideResponse * deltaTime))}, Delta: {1f - Mathf.Exp(SlideResponse * deltaTime)}, Delta Time: {deltaTime}, Slide Response: {SlideResponse}", slideSoundSource);
shell scarab
simple ruin
#

How do you guys debug a character controller that has recently started to randomly accelerate into shear infinity for no reason? I didn't change any of the code.

autumn field
shell scarab
cosmic rain
simple ruin
#

it just started happening randomly a few moments ago

cosmic rain
simple ruin
#

because why would the movement code break if I didn't touch it?

cosmic rain
#

The debugging procedure doesn't change regardless of what your assumptions are.

cosmic rain
wide terrace
#

Turn it off then back on again. If it's still the same, start looking at what the values are, and why 👍

autumn field
# shell scarab how does the math expression work? I'm not able to wrap my head around it. When ...

The t value is very small because it's happening every frame, but over time those small change result in it moving towards its target value and easing out as it approaches since t always moves it a percentage towards its target value from its current value, and that distance is getting smaller, it moves slower. So as you say, it never arrives, but if you multiply t by a large values it approaches quite quickly

shell scarab
#

I guess I don't understand the point of 1f - Mathf.Exp(-SlideResponse * deltaTime)

autumn field
#

Yea I might be bullshitting about that exp "responsiveness" part. I've just seen it done quite a few times in different articles/videos, but since you mentioned it I tested it and don't really see a big difference. It might have something to do with not surpassing 1 with t at low framerates

shell scarab
#

For example, why not just put 0.1 in?

autumn field
#
using UnityEngine;

public class SmoothLerpToMouse : MonoBehaviour
{
    public bool exp;
    public float speed = 20f;
    public float dist = 20f;

    void Update()
    {
        var screenToWorldPosition = Input.mousePosition;
        screenToWorldPosition.z = dist;

        var targetWorldPosition = Camera.main.ScreenToWorldPoint(screenToWorldPosition);

        if (!exp)
            transform.position = Vector3.Lerp(transform.position, targetWorldPosition, Time.deltaTime * speed);
        else
            transform.position = Vector3.Lerp(transform.position, targetWorldPosition, 1f - Mathf.Exp(-Time.deltaTime * speed));
    }
}
wide terrace
#

Nice visualization

simple ruin
#

at this point I'm at a loss for words, because that was a stable save, and I have absolutely no idea why its breaking all of a sudden

lean sail
#

This is the standard for "I changed nothing and it stopped working!" You either changed something, or it was always broken and you didnt realize.

simple ruin
plucky inlet
#

Or you used a new editor or packages updated themselves or what not, but if you dont have any repo going, only you can tell what has changed, which you cant obviously

lean sail
simple ruin
plucky inlet
#

Or refactor and be happy to learn something. We all have been there trying to fix broken code and in the end spending more time than refactoring it in a whole

#

Which would imply debugging anyways 😄

simple ruin
#

ive been here for a week of sleepless nights debugging and just when I'm about to push this shit happens

#

fuck this

cosmic rain
# simple ruin its so terribly designed I dont know where to start, fuck me

Start from thinking about the issue. Is it moving too fast? What is movement? Movement is the change in transform.position. it's either changed by your code or by one of the unity systems(physics, animation, etc..). Find what's moving the character. Then debug the involved values and see how they change and when.

plucky inlet
#

And please create a repo for your project

simple ruin
simple ruin
plucky inlet
#

So if you disable your character controller script, its not moving at all, right?

#

Also any logs in console?

lean sail
#

You could do a sanity check of restarting and even reopening scenes. I vaguely remember an issue I had, where my pc shut down overnight while unity was open. When I reopened unity, certain physics stuff were very buggy.

simple ruin
#

cant disable the character controller script since too many things rely on the script being defined

plucky inlet
#

Also debug.log your inputs coming in for your character to move. do they ever reset

cosmic rain
#

Other than that, you'll need to share more details about your setup.

simple ruin
#

well I found the source of the bug it seems

#

I had the camera set at 0.65 when its supposed to be set at y = 0 relative to the character

#

i don't know why setting it to y = 0.65 absolutely breaks my movement code but im so fucking tired I can't be bothered

cosmic rain
simple ruin
simple ruin
#

Anyways, why does GLTFast not render .gltf textures properly in the built version of my project?

placid summit
#

Not exactly code but can I manage multiple build versions for a project with different code defines and player settings? This seems a major omission

vague slate
#

Any idea what's wrong with this? I added this on my Volume profiles. But even when I enter them and all other effect pop, this one is fully ignored and I can't find a way to make it work.

    public class DirectionalLightEffect : VolumeComponent, IPostProcessComponent
    {
        public ClampedFloatParameter intensity = new(1f, 0f, float.MaxValue);
        public ClampedFloatParameter indirectMultiplier = new(1f, 0f, float.MaxValue);
        public NoInterpColorParameter color = new(Color.white);

        public bool IsActive()
        {
            return true;
        }

        public bool IsTileCompatible()
        {
            return false;
        }
    }
#

I have this, I 100% enter this volume (all other effects are visible), but all colors from VolumeManager.instance.stack.GetComponent<DirectionalLightEffect> are always default at whatever I specified by default (Color.white)

cosmic rain
#

The issues is not the question, but lack of context.

I'm sorry if that was too obnoxious to you.

knotty sun
#

A command pattern is not context sensitive but any implementation of it is

kind cloak
#

Hi guys ! I have a FPS issue... In my app, it's always at 72fps but, when i upload some files on my sftp server (asynchronously) in this moment precisely i have a frame drop below 60fps, and it's really annoying. Any idea why/how to fix this ?

cosmic rain
kind cloak
#

Yeah it's the upload function, but i dont know why since it's asynchrone. Maybe i didnt understand the asynchrone system well, but i had in my mind that was the answer to an issue like this

cosmic rain
#

And the code that is calling the function

heady iris
#

We cannot give you a meaningful answer without enough information.

empty dagger
#

i want to make a simple lidar touch application in unity anyone knows how i can do it??

lofty summit
#

I am playing a video in webgl (so, from URL) but before the video loads my render texture is black.
Can I fill the texture with a colour to display before my video loads?

fleet gorge
lofty summit
knotty sun
fleet gorge
#

dumb method: in start, write one frame to the render texture first. i'm not sure if video player writes to the render texture while its loading

plucky inlet
#

Hello swarmknowledge. I have a logic question about adding some kind of "editmode" to my application. Right now, I have different behaviours running in the scene and reacting to different roles. What I am trying to achieve now is some kind of editmode toggle, that just triggers certain behaviour. I want to make the footprint on each component as automatic and small as possible, so I thought about using an interface. What I am wondering is, is there any advantage in using this against just a global boolean, which I will just check on the components?

fleet gorge
#

use a global boolean, perhaps a static variable. in the update of each component, if editing you can just return immediately

lofty summit
fleet gorge
#

quick method would be to have a camera write to a render texture, and on the next frame you can stop the main camera from referencing the render texture.

it doesn't have to be your main camera either, it can be an orthographic camera somewhere in your world with an image plane in front of it

#

under Camera

#

even if no cameras are writing to the output texture, the texture won't change. so you can have the camera render for one frame and destroy the camera afterwards

#

could you take a screenshot of your editor with the bulletprefab and bulletrelease fields during runtime?

#

its possible that somewhere in your code, you call Destroy on bulletPrefab by accident

#

so its working now?

empty dagger
fleet gorge
#

to clarify you're getting the error even when bulletprefab and bulletrelease are set?

knotty sun
#

instead of just outputting text why not show which one is actually null?

fleet gorge
#

based on some research lidar can apply to multiple platforms, like android/iphone as well as embedded

empty dagger
fleet gorge
gray mural
empty dagger
empty dagger
knotty sun
#

ok so chances are somwhere you are destroying bulletPrefab instead of bullet

fleet gorge
empty dagger
#

okay ill look for it

fleet gorge
#

so theres a discrepency between whats shown in the editor and whats happening in game

#

do you know how to use vs debugger?

gray mural
#

You do

#

!code

tawny elkBOT
gray mural
#

That's what my previous message was about

knotty sun
#

so use a paste site

fleet gorge
#

gamedevleague paste site is goated

gray mural
#

No.

#

Haven't been following. What's the problem in your prefab not being assigned?

#

Can't you simply.. assign it?

#

"Bullet prefab not assigned." is what I was able to read from your previously sent error

#

bulletPrefab is only used 3 times in the script. I see no way for its assignment to be removed when entering play mode

#

Do other scripts interfere?

#

Or is it not assigned?

knotty sun
#

where do you Destroy the bullet? It's not in that code

gray mural
#

Please, show it

#

Please, show the bullet's inspector

#

And where it's serialized

knotty sun
#

Is bulletPrefab also a GameObject in the scene?

gray mural
#

So could you show both objects?

#

Both

#

Bullet and where it's serialized

#

Neither of both scripts should be causing the prefab to be removed

knotty sun
#

Try this.
Disable the Bullet script on the bulletPrefab and enable it on the instantiated bullet

gray mural
#

The gun shoots a bullet and its reference disappears?

knotty sun
#

exactly. So you enable the Bullet script on bullet when you Instantiate bulletPrefab

knotty sun
#

that is where you Instantaite is it not

gray mural
#

Also, is the bullet prefab even in your Assets?

heady iris
#

No.

#

because then the prefab instance would destroy itself after a few seconds.

gray mural
#

So you instantiate the bullet, and its reference disappears right away?

heady iris
#

update your Debug.Log calls to also include this as the context object

#

this will let you find out which object, exactly, is producing the message

#
Debug.Log("Foo", this);