#archived-code-general

1 messages · Page 345 of 1

naive swallow
#

Ah, okay, cool. So, it doesn't need to be in Assets, it'll work even from Packages, and won't revert on change

heady iris
#

If you need to stick with actual 2D physics buttons, I would add a singleton that does a Physics2D.OverlapPoint when you click the mouse.

mental solar
#

(except programmatically, add an EventSystem + PhysicsRaycaster + InputSystemUIModule inside Start)

heady iris
#

create an interface like IClickable and give it methods for "mouse down" (and "mouse up" if you want)

stark sun
#

does anybody know how can I make my ragdolls leg point towards mouse or drag it by cursor?I'm trying to make a 2d football game thats why I'm asking.

heady iris
#

that's how I'd do it if I couldn't just turn this all into genuine UI

mental solar
#

yyyeah so basically the "Do It All Yourself" solution

#

I'll think about it... thanks!

#

for now I'll just leave the old stuff and clean up unneeded buttons/axes in the old input system so that they won't interfere

heady iris
#

Alternatively

#

you can just use both input handling methods simultaneously

quaint rock
#

well its not a do it all yourself soultion, just gives you more control when you do the cast or overlap your self and call stuff on a interface

mental solar
#

this is what the game's doing right now, I've replaced all gamepad code to use the new input system because Unity's console packages really want you to use the new Input System for Xbox and Switch

#

but the mouse code is still relying on these OnMouse events

#

i've removed all calls to Input. and the only usage of the old input system right now is OnMouse

quaint rock
#

would remove all OnMouse events and only use the IPointerX versions

heady iris
#

they're box colliders and sprite renderers

quaint rock
#

those will work fine with virutal mouses

quaint rock
heady iris
#

I guess you can try to do it anyway

quaint rock
#

just add the correct raycaster

heady iris
#

it just feels incredibly janky

#

that's what nik did above

#

but it's misbehaving

mental solar
#

yep

#

the code:

heady iris
#

I'm guessing you have something that's getting in the way of the raycast. The Canvas probably has a GraphicRaycaster on it already

mental solar
quaint rock
#

its what i had to do to get virtual cursor working for a switch game, that used to use old input systme

mental solar
#

i have no idea why

#

¯_(ツ)_/¯

#

surely this breaks the eventsystem raycast logic somehow, but why OnMouse works then is a mystery to me

quaint rock
#

why so many graphic raycasters?

mental solar
#

I wish I knew, man

quaint rock
#

it should only be on the Camera you want to do the cast from

#

same goes for the 2 physics raycasters

mental solar
#

no I've only added one, to the main camera

quaint rock
#

also will want only 1 event systme

heady iris
mental solar
#

just kept trying between the 2d and the 3d versions, and also only one eventsystem in the entire game, linked to the input system ui input module

heady iris
#

you wouldn't need to reconfigure anything in the inspector

quaint rock
#

but yeah would be so easy to just implement a new interface

#

then have 1 central place do raycasting and call the interface methods

#

could leave the logic mostly the same

mental solar
#

hmmm I'll need to figure out which raycast logic/method the old OnMouse stuff is using just so I can do the dispatch manually with the new active input system handling

#

OnMouse... doesn't need a raycaster attached to a camera so how does it figure out which gameobjects are pressed 🤔

quaint rock
#

OnMouse... is older then the "new" ui system and those raycasters

mental solar
#

huh

quaint rock
#

its from before 4.6 when unity got the UI system people use the most now, which is what incudes the EventSYstem, and raycasters

heady iris
#

it's some weird built-in thing

#

there are a lot of ancient MonoBehaviour messages

quaint rock
#

its been recommend to not use the OnMouse... stuff for a very long time now

heady iris
#

i use almost none of them

quaint rock
#

iirc unity even warns about it on some platforms

heady iris
#

It's from the era of stuff like the light and rigidbody properties

#

the Whoopsie Era

mental solar
#

yeah if it's some cursed built-in checking instead of a normal raycast I can see why the new raycast thing breaks in this game

#

especially with all the graphics raycasters

quaint rock
#

pretty sure all it does is just cast from main camera, then call the message if its on the mb

mental solar
quaint rock
#

would just start implementing something and deal with edge cases as you get to them

#

either your own interface methods and raycast or using the exisitng raycasters

#

or even building a custom raycaster for event system

heady iris
#

Of course, this won't properly handle overlapping buttons (because this project is using 2D colliders for them)

#

If more than one Collider overlaps the point then the one returned will be the one with the lowest Z coordinate value. Null is returned if there are no Colliders over the point.

I guess it might sort of work!

#

only if the camera is pointing in the +Z direction

quaint rock
heady iris
#

it doesn't fire from the camera into the 2D physics world

mental solar
#

hmm I'll try checking for a left button press in some singleton, read the screen value, transform to world, then do OverlapPoint and print the name of the gameobject that got hit

#

if this will work correctly I'll hack my own event system then

heady iris
#

a 2D raycast just starts from some 2D point and goes in some 2D direction

quaint rock
#

ah yeah looking at my code i was using the event sytstems RaycastAll when i needed to manually do things but want to consider if UI is blocking or not

autumn field
#

Is there any way to use a Video Player with Timeline and have edit-mode scrubbing work? I tried the Default Playables sample from the Asset Store that comes with a video track, but that didn't work. I also downloaded the AVPro demo to see if their playable worked in edit-mode with Timeline, but no dice.

#

For context, I have a video file of a cutscene that I want to use as reference when rebuilding the cutscene in Unity with Timeline. It will be a total pain without some way to preview the video in the editor and overlay it on top of the game view. Overlaying a video works fine in play mode, but I need to see the video while doing stuff in edit mode. I can only find a bunch of old forum posts and scripts that don't work, but this seems like something you should be able to do haha

lucid zealot
#

Hello, how are you ? I'm following a course on Youtube to make a dialogue system and I try to implement some features in my code. The feature I want to add is a way to show the speaker on screen in the face box, the screen or both. Actualy my code work for just one or but not both. Can you help me please ?

Here is the tutorial : https://www.youtube.com/watch?v=-mn3M52uOPc

My difficulty is to show both, because my code work only for one and I don^t know how to keep the same logic but modify to have both

Let's configure our characters to spawn in the scene and create the functionality for them to show and hide themselves from view.

Other Links:

▶ Play video
#

If I need to resume, I have a prefab with name of the speaker inside the same folder logic for each speaker.
Dialogue Ressources/Characters/FACEBOX/Name and Dialogue Ressources/Characters/SCREEN/Name

I've got this code who take the file path for the prefab object (charFacePathPrefab = Dialogue Ressources/Characters/FACEBOX/Name/Name.prefab )
private GameObject GetPrefab(string characterName){

        string prefabPath = FormatCharacterPath(charFacePathPrefab, characterName);
        return Resources.Load<GameObject>(prefabPath);
    }

I'ld like to keep the same logic but modify the code to change the path to FACEBOX, SCREEN or Both. I don't know how to modify for both

and same thing for this code :
if(prefab !=null){
GameObject obj = Object.Instantiate(prefab, manager.charFacePannel);
obj.SetActive(true);
char_root = obj.GetComponent<RectTransform>();
anim = char_root.GetComponentInChildren<Animator>();
}
Where the manager.charFacePannel is the location to instantiate the prefab

#

CodeCopilot don't help me aha

trim schooner
#

!code

tawny elkBOT
rain junco
#

https://paste.ofcode.org/fH8srXsqbTMKs8sqryTqy2 so iam generating a area with blocks(stone) then changing them randomly and replacing them with ores(eachone has a start and end spawn height) but in the code when i rmove the waitforseconds(.3f) it spawns a kind of platform inone height only. And when i put the waittime it exits as it should

heady iris
#

Perhaps your BlockData component sets the position of the block in Start

#

Start runs before the first Update call, and that happens one frame after instantiation

rain junco
#

in start its only creating the default area 6610

rain junco
heady iris
#

Your code instantiates a bunch of blocks and then starts a coroutine.

#

I'm wondering if something is happening after the blocks are instantiated that's necessary for the ore generation to work right

#

such as, say, something done in BlockData's Start method

rain junco
#

ahh nope

heady iris
#

Perhaps the animations are trying to set the position of the root object?

#

that is, the object that has the Rigidbody on it

#

In that case, there is no reason whatsoever for the rigidbody to be making the animations look different.

#

Show your hierarchy and the inspectors for the objects with the animator and rigidbody on them

tawdry pecan
#

Hello. I am making an fps shooter and I have a problem with the weapon switching code. As seen in the video below, the weapons themselves work fine. But when I switch weapons, the knife stops working entirely but the gun works still

dusk apex
iron vortex
#

Anybody know anything about this concept?

public void MaterialTest()
    {
        materialInstance = new Material(material);
        material.SetTexture("_BaseMap", texture);
        Debug.Log("Material (" + materialInstance.ToString() + ") albedo map changed to (" + texture.ToString() + ").");
    }
#

It pretty much hotswaps a material's main texture to a different one

#

for some reason it persists in editor mode

#

for all I know this probably isn't even a good or efficient practice for changing a material's texture or just an object's material altogether

dusk apex
#

Did you want to change the material of the new instance or the original material (assuming the original material is an asset)

iron vortex
#

Well, it would have to be the original because I'm not sure how to change a mesh such that it uses a new instance of the original material

dusk apex
iron vortex
#

it is the asset itself yes

idle musk
#

Is there a way to only show the top part instead of all that other stuff in a Debug.Log for a Windows Server Build? Seems like alot of bloat for something I dont need to see unless I request for it lol.

idle musk
#

Thanks I got it 😄

#

Glad the editor has the ability to discern regular logging and such with it.

#

Thanks again @dusk apex

leaden ice
#

so you will be stuck with isAttacking == true forever

vale wharf
#

In my game, the player can stretch their bodies to sling in a direction(hold space and a directional key. Releasing only directional key causes stretching to recede). I want them to not be able to stretch through obstacles. Currently, I'm attempting to achieve this by doing a SphereCheck at the face bone position (which is always at the front of the player).

Issues with this approach:

  • The variable used to control the stretch animation's time still increases even if there's an obstacle preventing stretching which causes the player to 'snap' when receding
  • If the player fully stretches and then changes direction, they can still clip through obstacles

See gif for a (hopefully) clear demonstration of these issues.

Here's the relevant code (ran every frame):

stretchTime += Time.deltaTime; //Not relevant to issue, just a variable for debouncing other logic.

GameChainData state = GameChainManager.Instance.GetState();

Vector3 inputVector = cam.transform.TransformDirection(state.inputVector) * 2f; 
inputVector.y = 0f;


stretchVector = Vector3.MoveTowards(stretchVector, inputVector, 1f * Time.deltaTime);
stretchVector = Vector3.ClampMagnitude(stretchVector, 1f);

if (state.inputVector != Vector3.zero)
    owner.lookVector = stretchVector.normalized;


if (!Physics.CheckSphere(faceBone.position, .5f, LayerMask.GetMask("Obstacle", "Ground")))
{
    animator.SetFloat("StretchAmount", stretchVector.magnitude); //StretchAmount controls the time of the stretch animation.
}

How can I prevent the issues I've listed? A ray/sphere cast will fix the second one but I tried that and ended up with more issues relating to the snapping seen in the gif where stretchVector continues to increase even if there's an obstacle in the way.

weak spruce
#

I have problem with json file load

using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public PlayerData playerData;

    public void AddScore(int score)
    {
        playerData.Skoor += score;
    }

    private void Start()
    {
        playerData = GameObject.Find("GameManager").GetComponent<PlayerData>();
        LoadPlayerData();
    }

    public void SavePlayerData()
    {
        string json = JsonUtility.ToJson(playerData);
        SaveToFile("playerData.json", json);
    }

    public void LoadPlayerData()
    {
        string json = LoadFromFile("playerData.json");
        if (!string.IsNullOrEmpty(json))
        {
            playerData = JsonUtility.FromJson<PlayerData>(json);
        }
        else
        {
            Debug.Log("No data found to load.");
        }
    }

    private void SaveToFile(string filename, string json)
    {
        string path = Path.Combine(Application.persistentDataPath, filename);
        File.WriteAllText(path, json);
    }

    private string LoadFromFile(string filename)
    {
        string path = Path.Combine(Application.persistentDataPath, filename);
        if (File.Exists(path))
        {
            return File.ReadAllText(path);
        }
        return null;
    }

    public void DeletePlayerData()
    {
        string path = Path.Combine(Application.persistentDataPath, "playerData.json");

        if (File.Exists(path))
        {
            File.Delete(path);
        }
    }
}
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class PlayerData : MonoBehaviour
{
    public int Skoor;
}
#

the files save to json but dont load

somber nacelle
#

have you actually confirmed that the data was saved in the first place?

weak spruce
somber nacelle
#

and have you confirmed that the data inside that file is what you expect it to be?

somber nacelle
#

do you have any errors in the console

weak spruce
somber nacelle
weak spruce
#

I read it but I dont understand what i need to change

somber nacelle
#

Only plain classes and structures are supported; classes derived from UnityEngine.Object (such as MonoBehaviour or ScriptableObject) are not. Note that classes derived from MonoBehaviour or ScriptableObject can be used with JsonUtility.FromJsonOverwrite as an alternative.

ionic mist
#

Question about cameras and UI canvas
I have a UI canvas in Screen Space - Camera mode using a camera A.
is it possible for a different camera B to also see/render the same canvas? how? I'm having a hard time with this

gleaming imp
#

How is everyone using AI, LLMs, copilot, in their flow

vivid halo
#

@gleaming imp
I primarily use AI as an enhanced Google search, but I have to cross-verify with sources because the AI may be parroting incorrect information.

I set up my GitHub CI pipeline almost entirely using GPT to generate the boilerplate .yaml files, but I needed to hand-hold and do research on behalf of GPT so it could string together the correct commands. Even though it required significant oversight, it was still faster than me writing bash myself since I am not proficient with it.

It's okay in very small, defined scopes, and for solving problems for which there are many examples of solutions, but very bad at anything broader than the scope of two functions.

#

LLMs are good at drafting a lot of ideas and providing beginner-level guidance on many topics, but lack expert-level depth. It's basically a decent autocomplete in its current state.

cold parrot
flat cloud
#

guys how do I loop a statement a specific number of times in unity?

cold parrot
cold parrot
torpid depot
#

guys how can ı get only blue color transform position Vector2 or Vector3

#

that green point player and and ı do not want ınstantıate or other methods in green circle

#

any idea?

maiden heath
torpid depot
#

what you mean

maiden heath
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

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

maiden heath
#

take a basic tutorial please

#

scripts are the code and objects are the things

#

you attach scripts to objects to make them do stuff

torpid depot
#

wow

lusty zephyr
# torpid depot any idea?

Maybe a stupid suggestion, but I'd think that you could set the borders of the blue object and instantiate it. If it would instantiate in the green radius (aka. a certain distance from the center), then rechoose a position.

lusty zephyr
maiden heath
#

hes asking to get a position of an object

torpid depot
torpid depot
maiden heath
torpid depot
#

my englısh not very well btw

maiden heath
maiden heath
#

assuming you have a rigidbody and collider

lusty zephyr
lusty zephyr
#

then it spawns in the blue area yeah, but still the issue of the green spot

#

I think I had that problem before. I had a tutorial on how to fix it, but it was a long time ago

torpid depot
#

when player moves The green cırcle wıll move too wıth hım also

lusty zephyr
#

But he basicly "pushes" the spawned object

torpid depot
#

actually first step should push the spawned object and after that can clamp locatıon

#

even the spawned posıtıon out of blue area

#

ıt have to clamped in blue

cold parrot
lusty zephyr
#

AH WAIT. I have a project with that exact functionality. Let me open it real quick

torpid depot
#

yea it is worth actually

#

if object in the green it will find other position

#

do we know how to check in a circle area?

#

ı know only for cube area

mystic glacier
#

i got no idea if this is the right place, but ima ask anyway

if you were gonna make a multiplayer game, which method would you use
ive found 3 methods so far
unities inbuilt https://www.youtube.com/watch?v=fdkvm21Y0xE
photon hosting https://www.youtube.com/watch?v=y69wBS13wwA
steam hosting https://www.youtube.com/watch?v=7Eoc8U8TWa8

is there any other "better" one that you would recommend instead

any help appreciated, i am pretty beginner level at the intricacies of coding (not so beginner that i need to be told that multiplayer is above my capabilities)

knotty sun
last island
#

Is it possible to use Physics.BoxCast() outside of FixedUpdate?

mystic glacier
last island
#

Or would it not give the desired result?'

knotty sun
mystic glacier
#

ive evaluated myself, i understand the principles of all 3 methods, im just asking for an outside opinion

granite lance
#

Hello, I am in need of some help as I have no clue of what is happening here:
I have this Terrain (see image) where I added 4 high spikes for debugging reasons (orange vertical "lines"). My issue is that the actual heightmap modifiable space does not go all the way to the end of the terrain and I am very confused, can I force it to go all the way to the end?

knotty sun
mystic glacier
#

you see how i said "is there any other "better" one that you would recommend instead"

this is because i figured there would be other methods because im aware

i asked for options not a smartass responce saying "f you"

gleaming imp
mystic glacier
#

i dont see the point of you saying dont do that, if you dont want to help me learn, say nothing, if you do, help me, either way, dont tell people their not capable of something because thats how you stop new people from wanting to learn and making new potentially great games

vivid halo
#

Multiplayer is not quite a beginner-level skill. I haven't done it myself, but I would focus on building the core game mechanics first so the multiplayer is not on the table until later.

gleaming imp
#

i'm surprised there isn't already an off the shelf multiplayer package that does everything

chilly surge
#

"I'm surprised there isn't already an off the shelf game engine that makes the game for me" 😉

last island
#

Probably full of terrible, terrible games, moreso than today

gleaming imp
mystic glacier
last island
#

It won't replace game design knowledge

bold saffron
#

any of you guys know where i can find unity version 2017.4.9f1

mystic glacier
#

well yeah

last island
#

Even if you made a machine that could do everything perfectly, without good design it would still just produce bad games

gleaming imp
#

it's fine, the world is already full of something for everyone

#

i think, inevitibly, the future is AI augmentation

bold saffron
#

any of you guys know where i can find unity version 2017.4.9f1

last island
#

AI Augmention in the AR space, I would like more of

#

But this almost manic need to replace artists and engineers in games right now I don't get it

gleaming imp
#

but it's also inevitable that AI will become more capable and autonomous
not that removes the ability for artistic expression

last island
#

Unless we find a new way to make AI that is fundamentally different from the current GPT craze, then AI has plateud

#

We need another breakthrough or two

gleaming imp
#

supermaven uses a different tech other than transformers, alledgely better

last island
#

Allegedly

gleaming imp
#

we'll continue seeing that, in particular agentic workflows

last island
#

They all say that

#

Need results

gleaming imp
#

have you tried it in the IDE

last island
#

I have not.

gleaming imp
#

give it a go

#

i've got a bunch of todo lists

last island
#

The thing with code completion tools is that it's very dependent on the quality of the code it's trained on

#

Most code in existence is bad code.

gleaming imp
#

it'll take a lot of duct tape probably, but my expectation is it can do 80% of the work if you guide it well

#

if you pay for pro it adapts to your coding style

#

also claude artifacts is bonkers

dusky lake
#

Is there any good way to split code from client builds? My server and client are the same codebase with a switch in a scriptable object, now I'd like to not include my server code in the client build, is the only way a defined preprocessor var and #if blocks or do I have any other possibilities?

gleaming imp
#

you mean client - server architecture?

#

#if blocks seems adequate ig

dusky lake
#

yeah, I just dont want certain scripts in the hands of users (includes them just making an edit to the scriptable config and being able to boot a server) 😄

last island
#

#ifdef is your friend there

dusky lake
#

so no other way like excluding a full folder from building and just ifdef'ing the calls into that folder?

last island
#

Well

#

The other way is to build your server client and your user client separate from each other

#

What many would likely consider "the better approach"

dusky lake
#

the server reuses a lot of the client code, so unless i wanna sync a shared repo between the two there is no good way for me to split the projects

last island
#

Well if you have shared code you could make a git submodule and include the shared parts in both client and server project that way

#

It means you'd have to separate that code out into a library of sorts but I am guessing that is possible.

dusky lake
#

possible but from looking at it, it looks like more work than just ifdefing my way through it 😄

last island
#

Yeah but since you asked

#

Those are your two choices atm

dusky lake
#

i am guessing the compiler ignores code files that are not used (excluded by ifdefs)?

last island
#

As long as the code is valid in those files I guess. Otherwise they shouldn't be there.

dusky lake
#

wouldnt really help me if the calls are not made but the code is still compiled in there

young tapir
#

Is there a somewhat easy way to run a check once per frame without using Update()? I need to inherit from a script without that functionality

last island
#

How would you see that working?

#

You need to check every frame

#

Something has to call a method every frame somehow to make that check

dusky lake
last island
#

That's potentially a ton of event propagation

young tapir
dusky lake
last island
#

I suppose so

young tapir
#

Never actually used events before, outside of premade stuff

dusky lake
#

On first glance it looks good, cant verify as I am on mobile rn

gleaming imp
#

Wen discord AI runmycode

knotty sun
sleek bough
tawdry pecan
#

Hi again. I'm having a problem with melee hit detection. Upon left click, the knife will interpolate from swingStartPosition to swingEndPosition, carrying its big hitbox with it. Anything with the component "Entity" caught in the big hitbox will lose health. In the video I sent, the hitbox is clearly going straight through the entity but its not taking damage. The problem doesn't lie with the entity because the gun works fine on it

Here is all the associated code:
Entity https://hastebin.com/share/eyavewaray.csharp
MeleeDamage https://hastebin.com/share/aragupinos.csharp
MeleeController https://hastebin.com/share/ebisoyerom.csharp

dusky lake
tawdry pecan
#

The ball doesn't have a rigidbody but it has a box collider

dusky lake
#

does the sword have a rigidbody?

tawdry pecan
#

It also has a box collider

dusky lake
#

no rigidbody?

tawdry pecan
#

No rigid body here

dusky lake
#

two non-rigidbodies dont trigger events on each other

tawdry pecan
#

I can't make 2 box collider trigger each other?

dusky lake
#

not without one of the two having a rigidbody

tawdry pecan
#

Alright I'll see if it works

dusky lake
#

you can just give the sword a rigidbody and set it to kinematic

#

or give your enemy a rigidbody which he will most likely need in the future anyways (if you want them to move)

tawdry pecan
#

Oh wow it just works

#

Thanks!

#

Now I'm having a problem where in playmode the knife looks fine but when I do build the knife shrinks

#

Once again the gun is perfectly intact

dusky lake
tawdry pecan
#

Yes

dusky lake
#

did you create your knife in blender / 3d software?

tawdry pecan
#

Correct

#

I have the gameobject of the knife set scale to 1

dusky lake
#

rightclick -> reimport on the model

tawdry pecan
#

Oke

dusky lake
#

also make sure any scaling you do in blender is applied to the transform

tawdry pecan
#

Alright it worked

#

Thanks again

dusky lake
#

if there is any discrepancy between build and in-editor either reimporting or restarting unity is 99% of the time the right solution 😄

tawdry pecan
#

Noted 👍

scenic sigil
#

Why does this barely move my character?

rb.AddForce(new(8, 0), ForceMode2D.Impulse);
#

rb is Rigidbody2D

olive pebble
#

8 is not much !

scenic sigil
#

lets do 100

#

like it moves fine with 5 speed but addforce goes nah with 8

olive pebble
#

i usually go in the hundreds yeah

scenic sigil
#

even with 100 it still moves the tiniest bit

#

maybe it's about the surrounding code?

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

public class Player : MonoBehaviour
{
    [SerializeField] private float dashCooldown = 3f;
    [SerializeField] private float speed = 5f;
    private Rigidbody2D rb;
    private bool dash = false;
    private bool dashOnCooldown = false;


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

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

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && !dashOnCooldown) 
        {
            Debug.Log("Dash.");
            dash = true;
            StartCoroutine(DashCooldown());
        }
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float x = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(x*speed, rb.velocity.y);
        
        if (dash)
        {
            rb.AddForce(new(8, 0), ForceMode2D.Impulse);
            dash = false;
        }
    }

    IEnumerator DashCooldown()
    {
        dashOnCooldown = true;
        yield return new WaitForSeconds(dashCooldown);
        dashOnCooldown = false;
    }
}```
#

@olive pebble

olive pebble
#

looks like it's still 8 here

scenic sigil
#

the normal movement is fine with 5 speed

#

but dash is nothing with 8

olive pebble
#

yeye normal cause velocity and force is not the same scale at all

scenic sigil
#

should i also do velocity on dash?

olive pebble
#

I do it that way but it might not be the most rigorous way to do

#

Plus you're missing on the different force modes, if you wanted yo use one

scenic sigil
#

even this barely moves
rb.velocity += new Vector2(8, 0);

scenic sigil
#

it's probably coz of the surrounding code

#

because the main movement is okay with lower forces (5)

young tapir
#

For some reason this custom event I made doesn't want to work. I'm attaching the MonoBehavior to the player but nothing in the function seems to work, is there somethin' I'm missing?

olive pebble
tawny elkBOT
young tapir
#
  public class SkillStormCaller : SkillData
  {
        public static bool leftRaised = false;
        public static bool rightRaised = false;
        public static bool bothHandsRaised = false;
        public static float heightInput = 0.4f;
        public bool Example;
        public StormMono storm;
        public override void OnSkillLoaded(SkillData skillData, Creature creature)
        {
            Player.currentCreature.gameObject.AddComponent<StormMono>();
            storm.Loop += Storm_Loop;   
        }
        public override void OnSkillUnloaded(SkillData skillData, Creature creature)
        {
            storm.Loop -= Storm_Loop;
        }
        private void Storm_Loop()
        {
            if (Example)
            {
                Debug.Log("Event Works");
            }
        }
    }
  public class StormMono : MonoBehaviour
  {
      public event StormMono.UpdateFrame Loop;
      public delegate void UpdateFrame();
      public void Update()
      {
            if (Loop != null) Loop();
        }
    }
}```
#

Is that what you wanted?

scenic sigil
#

never post screenshots of code

olive pebble
#
  • you are overwritting your velocity with your horizontal movement
scenic sigil
#

i'm doing += not =

#

also you don't move vertically at all

olive pebble
#

I meant this

#

rb.velocity = new Vector2(x*speed, rb.velocity.y);

scenic sigil
#

what's wrong

olive pebble
#

if you have a dash going on it gets reseted to the default run speed

scenic sigil
#

huh

olive pebble
#

if you're are moving while dashing

scenic sigil
#

even not moving the dash barely does anything

olive pebble
#

still think it's because of this line, cause if you are not moving then your velocity would be set at 0 every fixed update

#

rb.velocity = new Vector2(x*speed, rb.velocity.y);

#

resulting in your velocity being set only on 1 frame, then redefined with this line

scenic sigil
#

oh yeaah

#

so how do i fix this

olive pebble
#

depends on how you want to handle it

scenic sigil
waxen socket
young tapir
scenic sigil
olive pebble
#

huh haven't thought about it for long but maybe don't set the velocity if it's higher than your run speed

#

you can check the abs of your velocity

waxen socket
scenic sigil
#

let me do that

scenic sigil
# olive pebble you can check the abs of your velocity
        float x = Input.GetAxis("Horizontal");
        if (Mathf.Abs(rb.velocity.x) <= speed)
        {
            rb.velocity = new Vector2(x * speed, rb.velocity.y); 
        }
        
        if (dash)
        {
            rb.AddForce(new(8, 0), ForceMode2D.Impulse);
            //rb.velocity += new Vector2(8, 0);
            dash = false;
        }

this works like a charm but dashing leaves some sliding and i want it to be instant

olive pebble
#

wym sliding ?

#

like it slowly decresease back to your runspeed ?

scenic sigil
#

hold on i need to replace the sprite

olive pebble
#

mb chief

scenic sigil
#

the recording is a bit wonky coz i messed up the obs scene

waxen socket
scenic sigil
#

maybe i should do MovePosition with Lerp

waxen socket
scenic sigil
#

doesn't get rid of the sliding

waxen socket
#

rb.velocity = new Vector2(x * speed, rb.velocity.y); this line will stop sliding as soon as it is called

olive pebble
#

in that case you should indeed do a coroutine

#

btw you can get rid of your dash bool variable and just put a function instead

eager steppe
#

Just a quick question: is OnMouseDown/any 2D collider supposed to be intercepting UI events?

For example if i have a sprite that debugs to the console whenever clicked, and it's behind a UI button, and i click said button, and the sprite debugs to the console; is that SUPPOSED to happen?

If not then would I have to use raycasts or something to make sure this doesn't occur? EventSystem.IsPointerOverGameObject() surprisingly always returns true in this case.

scenic sigil
#

jesus christ i accidentally made an infinite loop

olive pebble
#

💀

heady iris
#

it's its own weird (legacy) thing

eager steppe
#

💔 alr ty

heady iris
#

I'm surprised that EventSystem.IsPointerOverGameObject() is returning true all of the time though

#

I use it to prevent clicking from triggering an action in the game world if my mouse is over the UI

#

I wonder if you have a transparent Image that's covering your entire canvas

#

If it's a raycast target, then your mouse will always be hovering over something

#

If you're using the old input system, select the Event System object in the inspector and look in the preview pane at the bottom

#

it'll show a bunch of information, including what you're hovering over

#

for some reason, the new input system's input module shows a lot less information

#

If many enemies are going to share the same patrol route, I'd make a PatrolRoute component that holds the list of transforms

#

The enemies could then reference one or more patrol routes

heady iris
#

I've gotten a few user reports involving corrupted save files. It turns out that you cannot assume that writing a file to the file system will work (:

I'm planning to do this when I serialize the current save data:

  • Copy save.json.bak2 to save.json.bak3
  • Copy save.json.bak1 to save.json.bak2
  • Copy save.json to save.json.bak1
  • Write the new data to save.json

Then, when reading:

  • Try to decode save.json
  • If that fails, try to decode save.json.bak1
  • If that fails, try to decode save.json.bak2
  • If that fails, try to decode save.json.bak3
  • If that fails, just give up

If something loaded, overwrite all invalid files with the successfully decoded data

Is this reasonable?

#

This was prompted by a bug report where a user's stats.json file turned into...

#

127 null bytes, followed by a +

steady moat
#

You could just rename files though.

heady iris
heady iris
steady moat
#

Better, you could have a file that keep track of the "latest" save.

heady iris
heady iris
steady moat
#

This way, you do not need to rename them.

#

You can reconsitutate the file with guess at that point.

heady iris
#

I guess I could just give up and read the files in order at that point

steady moat
#

But, that would really be unlikely that it happens.

#

I would simply use order as you said.

#

Never overwrite the save I guess.

heady iris
#

yeah, I could store:

  • save.json <-- written every time you save
  • save.index.json <-- tells you the most recently written backup index
  • save.backup-X.json <-- written in round-robin fashion every time you save
#

so after five saves with three backups, you'd have:

  • save.json <-- save 5
  • save.index.json <-- tells you that backup-2 is the newest one
  • save.backup-1.json <-- save 4
  • save.backup-2.json <-- save 5
  • save.backup-3.json <-- save 3
#

Corruption of save.json would be recoverable. Corruption of save.json and save.index.json would result in save 4 being restored

steady moat
#

Is save.index.json really necessary ?

#

You can check the modified time

heady iris
#

I could also check that, yes

steady moat
#

Alteantively, you can increment the number each time and delete the oldest

heady iris
#
private static void Serialize<T>(T obj, string path, bool onlyCreate)
{
    EnsurePath(path);

    if (onlyCreate && File.Exists(path))
        return;

    var data = JsonConvert.SerializeObject(obj, Formatting.None, Settings);

    File.WriteAllText(path, data);
}

This is how I'm actually writing the data, by the way. EnsurePath creates directories if needed.

heady iris
steady moat
#

If this is such a rare case, you can also just create the backup. Never restore it.

#

A forum on internet where you explain how to restore manually.

heady iris
#

True. I could then tell the user "hey, figure this out"

#

I already have buttons to open the log and debug-output folders

#

I'm currently fixing the more catastrophic problem -- if it fails to load the stats data, the game breaks Grimace

#

it throws an exception and blows up the game controller's startup method

#

gonna add a TryDeserialize that can signal this failure more gently

steady moat
#

Good idea. \

heady iris
#

it's particularly embarrassing because the game only tracks one stat (number of times you've played) right now, haha

#

and I already had a similar problem: an older version of the game wrote an incompatible stats file to the same location, which I forgot about entirely

dire crown
#

How do I combine two quaternions? I want to first apply q1 and then q2 but I need them combined so I only have one quaternion

heady iris
#

Use the * operator.

#

q1 * q2 gives you the result of applying q1 followed by q2

dire crown
#

Nop, Im not getting the expected result

#

Im inside the shader scope btw

#

like, doing it in a compute shader

heady iris
#

so you have two float4s ?

dire crown
#

yup

heady iris
#

it gives you a qmul function

heady iris
dire crown
#

ah perfect, that seems to work

magic vine
#

Hello, im currently trying to program a system, with which i can figure out, who the nearest player in relation to a finish line is.
Im using the code down below and have added the script to the finish line (the game object in the scene).
However, the finish line only checks for who the nearest player is when the game starts, and doesnt update, even though i have put it in void Update. I´d appreaciate any help!

using System.Collections.Generic;
using UnityEngine;

public class FIndFirstPlayer : MonoBehaviour
{
    public GameObject[] AllPlayers;
    public GameObject NearestPlayer;
    float distance;
    float nearestDistance = 10000;
    
    void Update()
    {
        AllPlayers = GameObject.FindGameObjectsWithTag("Player");

        for (int i = 0; i < AllPlayers.Length; i++)
        {
            distance = Vector3.Distance(this.transform.position, AllPlayers[i].transform.position);

            if(distance < nearestDistance)
            {
                NearestPlayer = AllPlayers[i];
            }
        }
    }
}
heady iris
#

How do you know it isn't constantly updating?

leaden ice
#

what makes you think it isn't?

#

Also note that FindGameObjectsWithTag every frame will be inefficient, you could do it once in Start and reuse it for example

#

Actually I see the problem. You are forgetting to reset NearestDistance

#

It should just be a local variable

magic vine
#

Im looking at the inspector(this thing) and it stays the same all the time, even though other players are closer

leaden ice
#
    float nearestDistance = 10000;
    
    void Update()
    {```
Should become:
```cs
    
    void Update()
    {
       float nearestDistance = 10000;```
#

because right now you never reset it at all

magic vine
#

oooh, thanks for the tip, i´ll try that out!

leaden ice
#

make sense?

magic vine
#

yeah, i see what the problem is

leaden ice
#

wait you're also forgetting to actually update the neartestDistance variable at all!

#

in the loop

#
            distance = Vector3.Distance(this.transform.position, AllPlayers[i].transform.position);

            if(distance < nearestDistance)
            {
                nearestDistance = distance;
                NearestPlayer = AllPlayers[i];
            }```
You need this as well^
magic vine
rigid island
#

I don't like that our enemies look similar 😈
/jk

#

oh lol

#

btw you would have to convert the world position into a usable screenpoint

#

I forgot the process tbh cause I only did it once but I'm sure its out there

heady iris
#

oh hey, I was just working on my "vision alert" system this morning

#

The simplest thing you can do is to do this:

#
  • Vision Alert Marker <-- no components at all
    • Arrow <-- has an image on it
#

Position Arrow above its parent

#

Now when you spin the Vision Alert Marker, the arrow moves around

#

that way, you don't have to set the position of anything

dawn nebula
#

So I want to allow a user to add files to some folder in the built game's directory and for these files to be accessed by the game. What's the standard way to create a directory on build, and getting the path to it later?

heady iris
#

For a non-circle, you'll have to do a bit of math

knotty sun
heady iris
#

Finding an angular position on an ellipse isn't quite as simple as doing it on a circle

#

StreamingAssets is good if you want the game to start with some files -- they get copied straight from the StreamingAssets folder into a folder in the built game's directory

#

I wound up using a mixture of that and just putting the arrow directly on the enemy

#

When the enemy is less than 75 degrees from the direction the camera is looking, I compute a screen space position and use that

#

I lerp to an elliptical position past that point

#

That avoids the weird behavior you get at 90 degrees

#

(screen space positions shoot off to infinity)

dawn nebula
#

Thanks.

knotty sun
spark flower
#

hey guys, i have this code:

        currentScreen = _screen;

        for (int i = 0; i < screens.Length; i++) {
            if (_screen == screens[i].type) {
                screens[i].Activate();
            } else {
                screens[i].Deactivate();
            }
        }
    }```
but when i try to execute it with the Button component, this function doesnt show in the list. why is that?
#

ScreenType is an enum

heady iris
#

the zero-argument UnityEvent on Button (so, one that's designed to call functions with zero arguments) can only handle a few kinds of one-argument functions

#

I dunno if it can do enums at all

spark flower
#

it can i think, i remember doing enums as arguments

knotty sun
spark flower
#

but i think ive done button clicks with enums as parameters

knotty sun
#

you might think but I know

spark flower
#

ok

#

thanks

simple egret
#

Button click events do take parameters (from the UI), it's just that enums are not supported

#

"Simple" types that you can fill from the Inspector are supported: int, float, string, GameObject, Component, etc.

lapis walrus
#

Does anyone know why the unity Character Controller views this as a collision? the cube is at a Y of 3, the ground at 0, the height of the character controller is at 2. And i've tried moving the height test out by itself to make sure it was not some other collider near it

lapis walrus
#

wait let me go back to the pre-test

leaden ice
#

It's at 0.08 not 3

lapis walrus
#

oh the cube

leaden ice
#

Right now the height is 2, half the height is 1. Then the radius is .29 and the skin wiidth is 0.08 so you should be at a total of 1.37 units towards the ground

leaden ice
#

the ground is a cube?

#

what's the cube?

lapis walrus
#

ignore that player transform above, here's the correct one using my test area, which has the ground at 1 not 0. interestingly its at 1.08, and the cube is at 3, but visually the collider is much lower

leaden ice
lapis walrus
#

let me try a default cube

leaden ice
#

Also I can't tell if you're asking about it hitting the ground or the cube

lapis walrus
#

the cube sorry

leaden ice
#

So how do you know it's being considered a hit exactly?

lapis walrus
#

ground collision is working well, but like in that screenshot, its colliding with the cube

#

I can't go under it

unborn turret
#

Hi. Sorry to hijack the convo. Just got here and not sure where to ask. Working with unity VR and Oculus 2. How do find the way to increase run acceleration with the hand increase of speed and vise versa to slow a character down?

lapis walrus
#

here's side orthographic view, with a default cube set to 3, this is a collision

leaden ice
# lapis walrus I can't go under it

ok well if you're t 1.08, you have to add 1.37 to that for half the height + the radius + the skin width
So that puts your player's "top" at 2.45 units.

If the cube is at 3 units, if it's a normal unity unit cube it should have a lower bound of 2.5

lapis walrus
#

sorry the cube is grey its hard to see

leaden ice
#

so.. i'm not really sure tbh 😆

leaden ice
lapis walrus
#

yea that's my thoughts exactly

#

sure one sec

leaden ice
lapis walrus
#

was testing something out, its been disabled

#

yep, its the cube

hearty merlin
#

Hey, im working on a FPS game, but I dont know how to code. Therefore, im relying on ChatGPT to write the code for my game, but its not working. There is one script and one script only in my project and its the player movement script. Whenever i press play on the game, WASD work, but for some reason it automatically moves the player backwards and doesnt stop. I have been troubleshooting for hours, and cant find a fix. All i know is that is has to do with that script. Anyone experienced this before, and if so, how did you fix it?

vivid halo
#

General question about how any of you would approach this problem, since I solved it in an unusual way compared to most other problems:

Problem: The camera must be rotated on X and Y axis (both yaw and pitch), but the root player object is only supposed to rotate on the Y-axis (player model should not pitch up or down when looking up or down)

Initial incorrect solution: Rotate camera by (X, Y, 0) and rotate root player object by (X, 0, 0)

Reason initial incorrect solution failed: Since the camera was a child object to the root player object, the X-rotation would apply once due to copying its parent (the root player) object's transform. A naive follow-up solution rotate the player to align with the camera, but this would in turn rotate the camera as it is a child object of the player, causing a cycle of extremely fast, endless spinning)

Revised solution: Rotate camera by (0, Y, 0) and rotate root player object by (X, 0, 0)

Why it works: The x-rotation applies to the camera and the player while the Y rotation only applies to the camera, the child object.

vivid halo
hearty merlin
#

i send a pic of the code

vivid halo
#

!code

tawny elkBOT
vivid halo
# hearty merlin i send a pic of the code

It absolutely goes without saying that you cannot rely primarily on GPT to code. You should take time to learn how to code, and use GPT as one of many resources in which to learn. Using GPT to solve problems can introduce many problems of its own if you don't know how to validate whether or not the code is working.

Your very problem is evidence of this.

lapis walrus
#

@leaden ice btw I figured out whats causing it, its the step height. which unfortunately I'm not sure how to fix. I want a high step height because I want the player to walk up large steps (retro look, chunkier scale), but not get stuck under things you should be able to walk through

#

this says nothing about artificially raising your height, either

rain junco
#

ignore the true/false

heady iris
#

and where are you logging that value from?

rain junco
#

in the generateRandomOres

heady iris
#

        float t = Random.value;
        Debug.Log(t);

This?

rain junco
#

yes

heady iris
#

I see that you have some code that initializes the RNG commented out

#

are you sure you saved before you ran the game and got those logs?

lapis walrus
#

becuase you have to call Random.Next() for the next value

heady iris
#

no, Random.value produces a new random value

lapis walrus
#

just use Random.Range

heady iris
#

you're thinking of System.Random

lapis walrus
#

are you using it all in the same frame?

lapis walrus
#

it will give the same value over and over in the same frame

heady iris
heady iris
#

Random.value is a property. It runs a function that generates a random value and updates the random state

heady iris
#

If you ran this before each time you read Random.value, you'd get the same value out every time

rain junco
lapis walrus
#

ahhh yea unity enginge's changes the seed for you

#

or whatever, i always forget there's two Random classes lol

heady iris
#

it's not that it changes the seed for you each frame

heady iris
#

when you ask for a random number, the RNG's internal state updates

rain junco
heady iris
#

you can prove that you don't by searching your code for Random.InitState and Random.state

heady iris
#

ctrl-shift-F generally does a project-wide search in your code editor

rain junco
#

got it i had another file idk what i did f myself

heady iris
#

If you need deterministic RNG for this generation process, you shouldn't use UnityEngine.Random at all

#

Anything else that uses it will screw up the internal state

rain junco
#

yeah thanks tho

heady iris
viral silo
heady iris
#

Both of these will let you create your own RNG that only gets used by the generator

rain junco
#

thanks

#

i had another file permanently set initstate to 45

heady iris
#

You can also save the current RNG state and restore your own, use it, and then restore the original RNG state

#

but that's a bit of a pain in the neck

rain junco
#

yess

#

thanks

maiden stone
#

Hello everyone. Does anyone know how I can get the play-head position from an audio source? For example, how do I check the elapsed time of a song, to make something run after a certain position in the song is reached. Say a song is 3 minutes, and I want to debug.log "hi" into my output after 2 minutes of elapsed time.

#

How can I do something like this?

maiden stone
#

oh my god. how did I not find this

#

Thank you 😅

vestal geode
#

Non-random randomness

heady iris
#

I’m not really aware of “atomic writing” for filesystems

#

Where did you copy that text from?

#

this is talking about the general concept of an atomic operation, yes

#

theres no direct atomic write method in C# like python for example

i'm not aware of python being able to do this

cold parrot
heady iris
#

I see. Yes, writing the file and then clobbering the original is a decent idea.

#

Assuming that the write actually flushed to disk, it gives you less room for an inconsistent file state

cold parrot
#

that holds for any kind of atomic operation. It fundamentally depends on the physical reality of doing it. So it’s necessarily a hardware feature.

heady iris
#

note that this is not doing anything special that Python provides

#

the C# implementation would be almost identical, save for syntax and name changes

cold parrot
#

That’s not really guaranteeing anything though. It can still fail

heady iris
#

assuming the file makes it to disk, a crash sometime during the file move should be recoverable by the filesystem (thanks to journaling)

#

directly overwriting the file means that you're in danger the moment the file gets cleared, until you finish writing the save data

#

I'm not sure if I can reasonably test this, but I suppose it would be easy enough to implement

wary coyote
#
    private void PerformConditionCheck(ConditionData condition)
    {
        ConditionValidationData conditionValidationData = new ConditionValidationData {};
        conditionValidationData.condition = condition;

        Debug.Log($"ConditionValidationData created with condition {conditionValidationData.condition.conditionName} instance ID: {conditionValidationData.condition.GetHashCode()}");
        Debug.Log($"PerformConditionCheck: {condition.conditionName} instance ID: {condition.GetHashCode()}");
}

What are possible reasons why the hashcode of these two references of the same Condition class have different hashcodes?

#

This is an XY problem, my real problem is
guiConditionData.condition.targetCharacter.conditions.Remove(guiConditionData.condition)
this fails to remove the condition, when they should be the same condition, and I dont know why or how to debug to find the reason why

#

They're classes, classes are a reference type yes?

heady iris
#

how is ConditionValidationData defined?

rain minnow
heady iris
wary coyote
wary coyote
heady iris
#

zap

#

haha, that'll do it

#

sneaky clone

wary coyote
#

If I undo this sneaky clone, I am going to have a new problem occur which is that I need a clone of a condition in a different circumstance UnityChanThink

#

but I think I can solve that

#

with calling it manually instead of doing that hot mess

heady iris
#

Maybe you need to "copy on write"?

#

where you copy the object when you need to modify it

wary coyote
#

The problem Im facing and don't know how to solve is if I DONT do that clone method, somehow every condition is the same condition class

heady iris
#

Right.

#

Everyone references the same thing

wary coyote
#

and like I tried to solve it just now and its still happening and I don't know why or how to fix it UnityChanThink

#
            if (IsConditionValid(conditionToApply, targetCharacter))
            {
                conditionToApply.targetCharacter = targetCharacter;

                ConditionData uniqueInstance = new ConditionData();
                uniqueInstance.CloneConditionData(conditionToApply);
                targetCharacter.SetCondition(uniqueInstance);

                // Clear the current condition to apply for the next entry
                conditionToApply = new ConditionData();
                initiative.RequestUpdateSubscribers();
            }```
#

why was this insufficient to create a brand new unique separate class?

#

I made a whole new instance of the condition data, cloned all the values to it

heady iris
#

perhaps conditionToApply is the iteration variable of a foreach loop?

#

assigning conditionToApply = new ConditionData(); wouldn't do anything to future iterations

wary coyote
#

Oh uh I can link the entire code but this is an editor window gui panel thing

heady iris
#

otherwise, i'll need to see some more code -- the script this block is from, as well as the definition for ConditionData

wary coyote
#

Sure, let me find the code dump link

#

or is there something specific that is more useful

leaden ice
#

What is conditionToApply?

#

Is that also a class?

wary coyote
#

I cant find the link to the code copy paste websites

rain tide
wary coyote
#

I will try that, good timing 👀

rain tide
#

NP

wary coyote
heady iris
#

representation is immediately suspicious, because that's a reference type

#

(it's a GameObject)

wary coyote
#

This is why I had that clone method before, the clone method COMPLETELY solved all of these issues, but now I can't use it, and my attempt to remake it has failed

#

This worked to solve all my problems but I don't know why it did

pulsar river
#

Hello

wary coyote
#

this is so frustrating and I'm honestly too far gone into crisis now by how frustrated and distressed I am over this that I am not able to actionably work on this any further, which in and of itself only highens my distress.

Thank you for helping me on this but I have to shut everything down now because I am having a nervious breakdown

heady iris
#

Alright

wary coyote
#

I'm not able to disenguage like that, I will never ever be happy or calm again until I solve this 🫠

#

but being like this makes it impossible to solve

#

so its a recipe for a hellish vortex into crisis

#

(programming without mental health is a bad)

pulsar river
#

why don't you jsut go for a walk or touch grass

heady iris
#

When you're looking at the problem again, I'd look carefully at the timing of the original Clone() vs. the new CloneConditionData call

wary coyote
# pulsar river why don't you jsut go for a walk or touch grass

I've tried, every moment the entire time I will be spent ruminating, spinning my wheel, focusing on the problem, focusing on why its a problem, focusing on distress, focusing on trying to solve it. I just don't winde down like how other people seem to be capable of

wary coyote
#
public class ConditionData
{
    public int dc = 10;
    public AbilityScore saveType;
    public int duration = 10;
    public string conditionName;
    public RulesD20.Condition condition;
    public ConditionSaveContext saveContext;
    public Sprite conditionSprite;
    public GameObject representation;
    public CharacterActor targetCharacter;

    public DiceRollResult save1;
    public DiceRollResult save2;

    public ConditionData Clone()
    {
        return new ConditionData
        {
            dc = this.dc,
            targetCharacter = this.targetCharacter,
            saveType = this.saveType,
            duration = this.duration,
            conditionName = this.conditionName,
            condition = this.condition,
            saveContext = this.saveContext,
            conditionSprite = this.conditionSprite,
            representation = this.representation,
            save1 = this.save1,
            save2 = this.save2
        };
    }
}

public class ConditionValidationData : ValidationStackBaseAction
{
    private ConditionData _condition;
    public ConditionData condition
    {
        get => _condition ?? (_condition = new ConditionData());
        set => _condition = value?.Clone();
    }
}```
#

This is how the Clone code worked before I messed with it

#

this worked to solve all every of my problems
except created a new problem wherein I cannot remove my clone because its not in a completely different circumstance the same

heady iris
wary coyote
# heady iris where is `ConditionValidationData` in here, if anywhere?
public class ConditionValidationData : ValidationStackBaseAction
{
    private ConditionData _condition;
    public ConditionData condition
    {
        get => _condition ?? (_condition = new ConditionData());
        set => _condition = value?.Clone();
    }
    public override Guid Attacker { get; set; }
    public override Guid Target { get; set; }
    public override void UpdateChatlog(bool isSuccessfulSave)
    {
        if (chatlogContent != null)
        {
            chatlogContent.UpdateChatSetSaveResult(isSuccessfulSave);
        }
    }
}```
its a higher level container that contains the condition
heady iris
#

uniqueInstance gets passed to targetCharacter.SetCondition. Does that eventually wind up assigning to ConditionValidationData.condition?

wary coyote
#

this version of the code is after I messed around failing to fix my issue though, Ill try to revert it

#

This is also part of my problem

#

is that my codebase is paralyzingly massive

#

but I'm too stupid to write it any slimmer, I need everything to do what I need to do and I dont know how to accomplish it with any less

#

so like even to show you any of the things you're asking for as sprawling walls of text

#

like 50 methods deep across 5 classes

#

and I try to refactor to make that not the case

#

and all I get is now its 60 methods deep across 6 classes 🫠 anyways

#

My codebase has grown so large that I no longer remember or comprehend large swathes of it that I wrote weeks or months ago

#

so im fucked when anything goes wrong

heady iris
#

Are you using version control?

wary coyote
#

Yes, github

#

I can undo my changes but my problem exists in the past

#

unless you're trying to suggest something else

heady iris
#

Good commit messages can help you to remember why you did things a long time ago. If you don't have those, then you should certainly start writing them

#

(and, more acutely, this means you can cleanly undo all of your recent changes, yes)

rain tide
wary coyote
#

Ah okay, that's already a means of thinking I haven't ever even done. To me all github is is a place to store code and roll back to earlier code.
Like, maybe I am not understanding what you're trying to teach me

#

If I go into my old code, and I don't understand my old code, how does/what does gthub do to solve that? It will have comments on commits but its not going to explain my own code back to me? Maybe?

#

Like if I am confused by my own code, I don't understand how/why github fixes that

#

my brain is fried I think I linked the wrong code entirely in that screenshot

heady iris
#

Your commit messages should describe what you accomplished with that commit. You should also describe why you made those changes if it's not immediately clear.

somber nacelle
#

if you cannot understand your own code or why you wrote it, you should 100% be writing better comments

chilly surge
#

Git is a version control, so you are correct that it won't directly explain your code to you.
However if you use version control from the very beginning of your project, then every line of code must be added/modified/removed from a particular commit. Combine that with a good commit message, it means that you can use features like git blame, or simply viewing the timeline of a particular file, to know that which commit added the line, and you can read the commit message to understand the context of that code a little bit better than having literally nothing.

heady iris
#

This is particularly important if you have a lot of complex machinery.

heady iris
#

(although I just broke that by doing a few project-wide reformattings)

heady iris
heady iris
#

doing a huge reformat means that most lines were now most recently changed by the same commit

zealous kite
#

Yeah, I also need help with some code. Unity broke so many times for me. I am new to the Unity forum...

spring creek
chilly surge
#

Yeah git doesn't replace comments. Besides API comments, you should also have comments to explain the "why" of your code when it is not immediately obvious, or simply impossible to know by reading the code alone (eg fixing an upstream issue)

heady iris
#

_ = MainMenu.Instance;

chilly surge
#

But git is very useful for cases when the code was obvious in that particular commit, but stop making sense after later changes.

heady iris
#

(i forget if that needs a var; i'm not at my computer)

#

This causes the main menu to be instantiated from a prefab

#

It's very non-obvious, so I put a comment explaining that it actually has an effect

zealous kite
spring creek
#

Best to just post the question and be redirected as needed though

rain tide
zealous kite
spring creek
spring creek
rain tide
#

I just seemed a bit harsh for a simple mistake, but maybe that's just me.

spring creek
rain tide
#

Oh, then my bad.

wary coyote
wary coyote
spring creek
#

What? What a rude thing to say. I apologize.
I will say that bunp is generally extremely rude to people most of the time. So that sounds about right that they would say something horrible like that
Best for me to just block in return I guess

zealous kite
#

I am an intermediate coder, but I will ask anyway.

rain tide
#

Okay, this channel is for helping people, not arguing, I understand that I kind of started it, but still.

zealous kite
rain tide
#

Either way, opinions are opinions, I should respect that.

zealous kite
#

I am doing an RPG, and I am trying to instantiate the numbers when dealing damage. It is not showing up and I also had effects facing the wrong way.

chilly surge
#

It's not about telling someone they are a beginner or not, it's also about the quality of help they will receive in each channel. People who help in #💻┃code-beginner for example, have generally much better ways of words to explain concepts to a beginner than someone who usually helps in the other code channels like me. Sometimes when a question becomes clear that it's way below the level indicated by the channel, I just stop engaging because I simply am not good at helping stuffs like "explaining what a variable is." Directing people to the correct channel means not only the questions are in the correct place, but they will also get much higher quality of help. Don't take that as a sign of insult, I can guarantee you most helpers do that not because they are trying to make you feel bad.

rain tide
rain minnow
#

are you pooling the text?

zealous kite
rain minnow
#

show your code. did you follow any tutorial? i know there are dozens on this topic . . .

rain tide
#

Then they wouldn't have to be instantiated?

#

Unless you're using it for effect, and not ui.

zealous kite
#

to be fair, I am following a tutorial, and it is supposed to be for UI. but I have effects as well.

#

I feel bad now.

somber nacelle
#

you're gonna need to show relevant code

rain minnow
rain tide
#

Sorry, I don't quite fully understand your situation, so I'm just trying to ask general questions.

zealous kite
#

I am.. one moment.

zealous kite
#

One moment.

spring creek
tawny elkBOT
rain tide
#

So, let me try to understand, you're trying to create an effect with text as the damage you do to the enemies?

rain minnow
zealous kite
rain tide
#

Did you modify the prefabs transforms?

zealous kite
#

Not really.

rain minnow
#

still waiting for the code. that's the first place to start . . .

zealous kite
#

I am. I have a pastebin.

rain minnow
#

then we can deal with inspector/prefab setup . . .

zealous kite
rain tide
#

We're sorry, but the contents of the bin could not be found, or it has been deleted.

zealous kite
#

Wait. I got a pastebin.... went to the wrong one. uggg.

rain minnow
#

everything is there . . .

#
public class CharacterDamageUI : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI damageText;
    [SerializeField] float lifetime = 1f, moveSpeed = 1f; float textVibrations = .4f;

    void Update()
    {
        Destroy(gameObject, lifetime);
        transform.position += new Vector3(0, moveSpeed * Time.deltaTime, 0f);
        
    }

    public void SetDamage(int damage)
    {
        damageText.text = damage.ToString();
        float jitter = Random.Range(-textVibrations, textVibrations);
        transform.position += new Vector3(jitter, jitter, 0f);

    }
}```
rain tide
#

It works now.

rain minnow
somber nacelle
#

gonna need to see what actually instantiates it too

zealous kite
#

Oh... I am posting that... hastebin is not working.

somber nacelle
#

but yeah, that Destroy call should be in Start not Update

rain minnow
#

from the snippet above, i removed the Start method because it was empty. that is where Destroy should go . . .

zealous kite
#

It instantiates a text

rain minnow
#

so the text does appear? does it move?

zealous kite
#

Nope. it does nothing.

rain minnow
#

if this is UI, you shouldn't update the transform but its RectTransform . . .

zealous kite
#

yep, the tutorial calls for the instantiation of a canvas with UI, so yes this is UI.

spring creek
#

Is lifetime set to 1 in the inspector as well?

zealous kite
#

Yes.

#

I was honestly trying to find a better way of making the text show when dealing damage.

#

I veered from the tutorial a bit.

spring creek
#

I am not seeing the instantiate code. Are you saying the OBJECT is actually instantiated, you just can't see it? Sorry I'm in and out so much. Multitasking

zealous kite
#

I do not know why this says java, but this is the code.

#

The "Character Damage UI" value, is what supposed to instantiate the canvas. Also, I do have another issue.

rain minnow
#

instantiate the canvas? the canvas should already be in your hierarchy. there is no need to instantiate one . . .

zealous kite
#

This is a tutorial, but I will veer from it... it is not doing me any good with this code.

rain minnow
zealous kite
#

Hmm... I see. I will find a way to instantiate it and set it inactive.

#

Putting the code on start did help.. thanks. it is still not showing up.. I feel very stupid.

#

But, I am here on a bigger problem though....

rain minnow
#

when the damage text is instantiated, does it appear as a child of the canvas?

zealous kite
#

Hmm yes!

rain minnow
#

weird, i don't see where you parent the damage text to the canvas or where the canvas is created at all . . .

zealous kite
#

I created a canvas, and the text is under that canvas in world space. I am instantiating the whole thing.

#

The Prefab is a Canvas with Text under it, sorry, that is what I mean.

rain minnow
#

wait, what? damageText1 prefab is a canvas, not a GameObject with a CharacterDamageUI on it?

zealous kite
#

Yeah, It is a canvas object with UI in it.

#

Yeah, that tutorial is on something else.

#

Also. The other problem.. where do I go, if my game keeps crashing.

#

I was also using git as version control.

spring creek
somber nacelle
#

define "crashing" because 9 times out of 10 when people say that here they actually mean it just freezes. and that is usually caused by an infinite loop

spring creek
#

Freezing then. I would say infinite loop like box said.
Got any while loops in update? That is a common one

#

I have also forgotten a yield in coroutine loops too, which caused it

zealous kite
#

I have a lot of for loops.

rain minnow
#

what code did you add or change before it started freezing?

zealous kite
#

I am so sorry... I do not know how to ask for help..... This is a little intimidating.

rain tide
zealous kite
#

I actilly sarted when I had created an inventory script and I was trying to create the menu, and it actually closed and froze on me. It is incomplete, but I will show the script.

spring creek
spring creek
rain tide
#

Yeah, but I can wait, I'm taking a little break from working on my game for the afternoon, so you're all good.

zealous kite
#

First problem was that I tried to create a menu that you can switch from viewing stats, to items. I was making the UI and it froze on me. I do not know if it was even the code, or my level.

#

For context, I am making a top-down RPG. I got the basics down(only thing i need is to handle how to use magic and items in battle and I am good).

zealous kite
#

I sent Unity a report about it.

rain tide
#

You're good, I'm just having problems with simulated Newtonian physics, foux gravity, and movement playing nice with eachother.

zealous kite
#

movement, what type of movement?

rain tide
#

Planet-based movement, using foux gravity temporarily until I can get my simulated gravity I use for my planets to work with my movement script.

zealous kite
#

you are moving them with the transforms correct?

rain tide
#

I think.

zealous kite
#

are you trying to make them rotate while moving?

rain tide
#

Well, I'm trying to change the transform.up to face the center of the planet.

#

Other than that, no.

zealous kite
rain tide
#

Can you explain what I did wrong?

rain minnow
somber nacelle
zealous kite
#

Are you facing in world space or local space?

rain tide
#

That's not when I originally asked for help, I've asked twice, and didn't get an answer, so sorry for you not liking the way I asked.

somber nacelle
#

cool since you don't want to provide context for your issue i won't help you 🤷‍♂️

#

"here's 200 lines of code. explain what i did wrong. no, i will not say what isn't working the way i want"

rain tide
#

And I thought ChillHound was saying that it was a direction issue, and he found the source of the problem, so my bad.

zealous kite
spring creek
rain tide
#

It flips whenever I move, I think it may be an issue with how I calculated the directions when moving.

zealous kite
#

do you have a reference to the objects direction?

#

Vector3 gravityUp = (transform.position - transform.position).normalized;
Vector3 localUp = transform.transform.up;
DirToPlanet = (transform.position - rb.position).normalized;
transform.up = DirToPlanet;

#

This needs to be the center of the planets position minus your position

zealous kite
#

do you have a constraint on the Z axis

spring creek
#

I'm wondering if it is the MoveDirection fighting with the AddForce calls
MoveDirection is for Kinematic rbs, and is basically teleporting

muted patrol
#

I have some questions about nav mesh, I understand how to bake a surface mesh and agents etc, i just dont understand how to set certain walkable slopes, or if i want an agent to be able to fall off the side of something

rain tide
rain tide
lean sail
#

you should really add debugs to your code, because you'd very quickly see where issues are like
transform.position - transform.position

spring creek
rain tide
spring creek
#

Hmm, actually DirToPlanet is quite odd
You are doing THAT objects transform position minus THAT objects rigidbody position (which should be the same)

lean sail
#

well debugging wouldve quickly showed u that the vector was 0

rain tide
#

Sorry for the hassle.

spring creek
#

Oh, laggy from going back and forth. Missed all that.
Glad it is figured out

zealous kite
#

Vector3.up, try that.

rain tide
#

It wasn't that, but it was related, I feel so dumb, the RB is the players rb, so when I did transform.position - rb.position, it was 0, because the rb is the players rigidBody.

#

Thank you everybody, and sorry for wasting your time.

zealous kite
#

No need, it happens, I can relate. I can't instantiate a text object properly and my UI is not functioning.

rain tide
#

🤦‍♂️

zealous kite
rain minnow
#

i mean, a rb field inside of the PlayerController script sounds like the player rigidbody . . . 🤷‍♀️

rain tide
rain minnow
#

if not, then i'd expect a more concise field name . . .

rain minnow
zealous kite
#

It happens, I was stuck on a code for 3 days and found out that the execution order was wrong in the code.

spring creek
rain tide
#

I was so focused on it being a rotation issue, that I ignored the most basic errors.

zealous kite
zealous kite
rain tide
#

I'm just surprised fresh eyes couldn't figure it out at face value(Not trying to be mean)

#

Again, thanks everyone for deverting your time to an issue as simple as this.

zealous kite
rain minnow
#

though, both of you are fine. it happens. at least some of your problems/issues are fixed . . .

zealous kite
rain minnow
zealous kite
high crow
#

i just need some help with cloning a 2d array of a class called cell right now im using gm.board.Clone() as Gamemanager.Cell[,] but some how when i change this it still changes the original one

fresh nest
#

The first one I get when I hit play and start up the scene, the second I get whenever I try to click on a non-traversable node

dusk apex
tawny elkBOT
dusk apex
#

You'd use the large code blocks guidelines (inline would be for small snippets of code only)

raven orbit
#

so im looking at a question on stack overflow and theres different answers, should i just try understanding one of the easier ones or complex ones so i could learn more

#

i started unity yesterday if that changes ur answer

dusk apex
#

Where the position on grid has a value that was greater than maximum x or y

fresh nest
#

That I got, but I'm trying to figure out why any of my scripts would by trying to interact with a position outside of the grid

leaden ice
fresh nest
leaden ice
#

How to do what exactly

#

Debug.Log?

#

That should be the very first thing you ever learn in Unity

fresh nest
#

How to specifically log the positions that it's trying to index

leaden ice
#

Debug.Log($"The position is {positionOnGrid}");

#

Just... Log it

hot sorrel
#

is there a way of serializing types on a monobehaviour with the functionality that you could somehow drag and drop type values like you would for a transform in the inspector? i would like to be able to instantiate objects of said types on start/ awake

leaden ice
#

Where would you be dragging from

hot sorrel
#

so i would have a class definintion and a scriptable object with a reference to the class type?

leaden ice
#

I'm not sure I follow that sentence

fresh nest
hot sorrel
#

public class sampleclass { // definition } -
public class scriptablesampleclass : ScriptableObject { public Type = typeof(sampleclass) }

@leaden ice

leaden ice
#

Wherever the exception is being thrown

leaden ice
#

Just one type

#

The ScriptableObject

#

Ok I think I'm just now understanding your original question

hot sorrel
#

wouldnt the state then be global and i couldnt have multiple instances?

leaden ice
#

You want to serialize a C# type

hot sorrel
#

yeah

leaden ice
#

Does it need to work at runtime?

hot sorrel
#

yeah

leaden ice
#

What's the end goal here?

#

What are you trying to ultimately accomplish

hot sorrel
#

final design not known for sure but say id like to be able to instantiate a number of different classes on awake/ start/ in response to input events and the classes that will be instantiated can be changed through the inspector instead of modifying code

leaden ice
#

The simplest approach is to just use prefabs

#

But you could also do this through Editor scripting

#

I.E. search your assembly for Types that satisfy some criteria and populate a drop-down with them

#

Then serialize the chosen fully qualified type name as a string

hot sorrel
#

if i were to do prefabs this would just be empty game objects with the class attached as a monobehaviour?

leaden ice
#

Sure something like that

hot sorrel
#

mmm i think i like your second way more

#

ill look into it, thanks plenty

leaden ice
#

Or just use an enum

#

And have a mapping in code from the enum values to the types

sly pilot
#
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
 EditorSceneManager.SaveOpenScenes();

Anyone have a clue why this takes very long? When I manually save, the save takes around 8-10minutes. It's a very large scene. When I do it with this function, it takes 1h30?

boreal jewel
#

for some reason, setting the velocity of a gameObject to 0 doesn't stop it. does anyone else have this problem?
(btw, no script directly changes its coordinates)

pallid stirrup
#

Hi guys, I have a question regarding the overall structure of a script.

In my games I have coins that, when close to the player, they gets pushed towards him. Once its close enough, the coin will disappear and the player gets a point.

The problem is that I feel like the script is mixing two things: pushing a gameobject towards a player, and assigning a point to their score. I've looked around, read about delegates but I'm not sure if that's really the way to go.

Could you take a look and tell me what you would do?

https://hatebin.com/lqsqhvdfcp

#

My problem lies in line 24

boreal jewel
#

Personally, I don't think it poses much of an issue. It's not the best practice to put everything into 1 script, but in this case, it's only 1 line of code. And it helps to have only 1 script to know where to look if you have a problem.

#

If the coin isn't a prefab, I'd say ditch GetComponent and use a serializeField to drag the ScoreManager into the script(in the unity editor)

#

getComponent is expensive

waxen socket
boreal jewel
waxen socket
#

I would replace OnTriggerStay with a OverlapSphere for attraction and OnTriggerEnter for adding score

boreal jewel
#

(im new btw, sorry if im incorrect)

waxen socket
#

You really don't want to have a ScoreManager dependency in the Coin class. I think coins should be as independent as possible

boreal jewel
#

why?

pallid stirrup
#

Thanks to the two of you :))
I'll keep your comments in mind regarding the GetComponent @boreal jewel and I'll go with the OverlapSphere + TriggerEnter. Thanks!!!

waxen socket
# boreal jewel why?

So you can spawn coins and place them wherever you want. Currently it is kinda independent because you have a tag check and GetComponent, if you were to switch it to SerializedField you will lose the ability to create new coins. Also a side note: if you do a tag check and a GetComponent after that, you can skip the tag check and just use TryGetComponent

boreal jewel
#

he can just duplicate

waxen socket
waxen socket
boreal jewel
#

ur right

ebon leaf
#

restart scene button works only once after applying dontdestroyonload()

works fine for other levels but not for level 1

mint cosmos
#

Or unity has check to not load the same scene and that's what prevents it from restarting

waxen socket
ebon leaf
#

ohh you're right, the script was attached to the camera which gets reset

ebon leaf
waxen socket
ebon leaf
#

thx alot for the help man 🙂

pallid stirrup
waxen socket
trim schooner
#

This is a code channel, at that is not a code question. Delete and ask in #📱┃mobile

molten thicket
lean sail
pallid stirrup
#

Ok thanks 🙂
I've ended up doing just that but adding a masking layer to the OverlapSphere which came in handy

worn star
#

i wanted to know if there is way to calculate the time it took to perfrm a jump

cosmic rain
worn star
#

life if a log the time only when its in contact with ground

cosmic rain
#

As a class field

#

For future reference this qualifies as a beginner question.

nocturne wyvern
#

i try to obfuscate my code with plugin on unity asset store and i have this error. How to fix this?

hearty merlin
#

!code

tawny elkBOT
hearty merlin
#

Can someone tell me how to share my code here? The !.code thing doesnt work for me (it probably works but I just dont know how to do it)

steady moat
#

It does work... You need to follow the instruction.

hearty merlin
#

Thats why I said it does work I just dont know how to do it. Ive been here for like 30 mins trying to understand the instructions, but nothing works. Thatswhy im asking for help

heady iris
#

I don't understand how these instructions are too complicated.

#

You go to https://gdl.space. You paste your code into it. You hit save. You copy the link.

hearty merlin
#

oh ok, i was trying to inline it but my code probably is too long for that

#

Anyways, can anyone tell me whats wrong with my movement script? whenever i try to press play in the editor, the player automatically starts moving backwards without any input. all my troubleshooting has failed.

https://gdl.space/zahoyokobu.cs

heady iris
#

I see you're logging the input values

#

Are they both zero?

hearty merlin
#

no. ill send a pic of the log in a sec

hexed pecan
#

Do you have a controller connected to your computer?

heady iris
#

(or even a controller not connected to your computer?)

hearty merlin
#

Here’s the log:

hearty merlin
#

if this is it im going to feel so incredibly stupid but hol up

#

nope it wasnt the problem

#

anyways, i have a xbox controller and a steering wheel, neither of which are connected to my PC

heady iris
#

also, please take screenshots instead of photographing your screen..

hearty merlin
heady iris
#

okay, so the vertical input looks like it's stuck

swift falcon
#

Hello!

heady iris
swift falcon
#

can i get help with something?

heady iris
#

I've had problems where a disconnected xbox controller produces phantom sticki nputs

heady iris
swift falcon
hearty merlin
swift falcon
heady iris
swift falcon
#

WAIT WHAT

#

WHY CANT I SAY "ANYWAY

#

WTH

heady iris
#

because the server expects you to write complete messages

hearty merlin
#

messed around with the steering wheel for a min, still have a input

dusky lake
#

Do you use input system or the old input stuff?

hexed pecan
#

They use the old system with Input.GetAxis