#archived-code-general

1 messages Β· Page 96 of 1

deep oyster
#

hmmm

languid crane
#

the other side inverted, as it should

normal cedar
#

Sometimes, z axis of pos gives me neg value, but I look at the indicator (it's in my camera view) and vice versa:
Code:

var pos = renderer.GetRectTransform().InverseTransformPoint(renderer.camera.WorldToScreenPoint(indicator.transform.position));
#

What's the problem?

dusk apex
# normal cedar What's the problem?

That's something you need to tell us. What's happening that shouldn't be happening. What's not happening that should be happening? What're you trying to do? We can read the code fine. We can assume your underlying intentions but that isn't something we're wanting or should be needing to do. Just tell us what the problem is.

prime rose
#

hi, I can xpost this to #πŸ“²β”ƒui-ux but I'm having an issue where a button is staying highlighted after it's clicked because it disables its parent object as a result of the click. Is there a way to "force" its state back to normal?

dusk apex
prime rose
#

I was hoping to set its state back to normal through code yes

dusk apex
#

Have you implemented this already?

#

Is it an issue with code? Or with design?

prime rose
#

I wasn't able to find anything in the documentation about setting a button's state

dusk apex
normal cedar
#

I know that FixedUpdate is for the physics calculations, but it solved the issue.

#

So!

dusk apex
#

Oh well. Simply going to inform you that you never stated a problem to begin with.

prime rose
#

is it really necessary to be this passive aggressive when people are asking for help?

thin aurora
dusk apex
#

Example: "When I press jump my character jumps 10 units. The inspector shows this to be true. Here's some code. What's the problem?"

#

It isn't very useful.

normal cedar
thin aurora
#

That's fine

normal cedar
#

I did update of indicator in Update.

dusk apex
thin aurora
#

Also fine

#

But this message tells me you moved code to FixedUpdate for it to work

normal cedar
#

But I had this problem.

thin aurora
#

You should only do that for physics calculations

#

Well I don't know what the problem is, do I?

normal cedar
#

I use code from the HUD indicator asset.

thin aurora
#

I cringe when people say they used code, I hope you know what it does πŸ€”

normal cedar
#

And it solved the task ideally.

#

But was that strange behaviour.

normal cedar
thin aurora
#

Yeah that's one way of saying it

#

Until you run into errors, and you are forced to copy paste your code into FixedUpdate for it to work

#

But hey, as long as it works right?

normal cedar
#

It works not perfectly.

#

So.

#

Compromise at this case.

thin aurora
#

I suppose compromises must be made when you copy paste other people's code and you're not sure how to fix it

normal cedar
daring lake
#

i used this function but when the bullet hits the player with the tag, it doesnt destory the bullet

vestal crest
#

are you sure this scope works? you can check by using debug.log or take a look at players health if the took any damage then its working

dusk apex
vestal crest
#

be sure of it by logging or looking at players health

daring lake
#

nothing shows up in the consokle

#

*console

swift falcon
#

if i instantiate a particle prefab when i collide with something, how should i be destroying the particle after its particle cycle has finished

#

because rn it just kinda sits inside the inspector as an instantiated object

#

unity wont let me just called Destroy on it

frosty lark
swift falcon
#

yes one moment

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

public class BulletProjectile : MonoBehaviour
{
    private Rigidbody br;

    [SerializeField]
    private Transform hitBullet;

    private void Awake()
    {
        br = GetComponent<Rigidbody>();
    }

    private void Start()
    {
        float speed = 40f;
        br.velocity = transform.forward * speed;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent<BulletTarget>() != null)
        {
            Instantiate(hitBullet, transform.position, Quaternion.identity);
            // Destroy(other.gameObject);
        }
        Destroy(gameObject);
    }
}

swift falcon
#

alrighty ty

#

what i also want to know is why its also instantiating 2 prefabs? πŸ€”

hexed pecan
swift falcon
#

ah yes

hexed pecan
#

It would have to happen in the same frame in this case

#

But its possible

steady granite
#

Modifying Script Execution Order only impacts order for the same functions, right? Meaning if a -1 priority an 0 priority scripts are in a same scene, they will execute Awake() -1 first then 0, and only then, they will execute OnEnable() if enabled? In my case I have a Script triggering OnEnable() before my other script has triggered its Awake()

swift falcon
#

i do have 2 colliders 1 is for a trigger and 1 collider

#

some reason they were both checked as istrigger

deep pendant
#

guys i'm really struggling with something, i'm making an idle game in the style of cookie clicker but i'm really struggling how to handle the larger number, and how to display them as like "thousand" and "million" without hard coding it and incrementing the number into a new variable each time. anyone know how to do that?

analog relic
analog relic
wintry crescent
#

Hi, I'm calling this function in my Update()

private void SaveSamplesToFile()
    {
        if (gestureSamples.Count == 0)
        {
            return;
        }

        string directory = EditorUtility.SaveFilePanelInProject("Select File to Save Data", "NewSample01.json", ".json", "Please enter the file name to which the sample will be saved.", defaultSaveFilePath);
        if (directory.Length == 0)
        {
            // User cancelled the selection, do nothing.
            return;
        }

        string json = JsonUtility.ToJson(gestureSamples);
        File.Create(directory).Dispose();
        File.WriteAllText(directory, json);
        Debug.Log("File saved to " + directory);
    }

unfortunately, I can only close the window that pops up, I can't actually select any file to save. Does anyone know what's happening? The docs are useless here

wintry crescent
signal shoal
#

I have a game with a primitive code editor that allows dragging and dropping commands into pre-existing slots in a "program" that users can run.
I'd like to rework this so users can drag commands into an editor area and drop them above or below other blocks (they then snap together).
Right now I'm considering having a "line of code" prefab that's created whenever necessary, with a snapping slot (I've already built) for each line.
However, I really don't think instantiating and destroying prefabs that often would work out well.
All boiled down: What is your suggestion for how a stack of vertical gameobjects can be rearranged, inserted, removed etc. in a way that won't impact performance terribly?

thin aurora
#

Also, where did you put the Debug.Log?

scarlet nimbus
#

Why does my Entities package not include TransformAspect cs? Using 2022.2 and 1.0 dots

thin aurora
wintry crescent
thin aurora
#

Well JSONUtility is a very shit tool

#

There should be a NewtonSoft.JSON Unity package

#

Otherwise you can download the Newtonsoft.JSON DLL manually (Just make sure you take the .NET Standard 2.0 version), and place it in a plugins/ folder.

wintry crescent
wintry crescent
thin aurora
#
var anonObject = gestureSamples.Select(x => return new {
    field1 = x.field1;
    problematicField = new { x = problematicField.x, y = problematicField.y, z = problematicField.z }
});

I didn't expect this would even be required, but here it is

grave hazel
#

Has anyone ever had the system call/load a 3d model from url into Unity at runtime?

so a project that has become apk can call a 3d model from the url (loaded from the internet)

I want to create such a vr presentation by calling the 3d object from url

tacit nest
#

someone help me to make a character jump because in my code when it jumps it doesn't come back down

desert shard
#
if(input.getkeydown(jump))
{
  rb.AddForce(Vector3.up * thrust, ForceMode.Impulse);
}
#

done

knotty sun
tacit nest
#

but I have to create some variable?

desert shard
#

do you?

trail finch
#

I want to convert the game to an apk file, but I'm getting an error like this, how can I solve it?

knotty sun
trail finch
knotty sun
trail finch
knotty sun
steep herald
#

Is there a way for a prefab to not serialize one of its fields, but retain the scene's serialized value?

knotty sun
steep herald
#

Yeah that was unclear, apologies, let me try that again

hallow meteor
#

Hello, if i make a thread with a while loop inside, will it take alot of performance?
In trying to make a thread that listen to editor camera's movement and other stuff like check if any object moved in editor mode.
But idk if using a while loop in a thread will take alot of performance or not. If it does, is there anyway else i could reduce the performance?

trail finch
knotty sun
steep herald
#

If I drag a prefab in the scene at editor time, and I modify one of its fields, I'd be able to hit apply to modify the prefab. What I'm trying to do is mark certain fields to avoid having them be part of the prefab's serialization process. The idea is to be able to do per-scene tweaks without risking overriding the values in other instances scattered across the game.

knotty sun
steep herald
#

Okay, thank you

noble sedge
#

Guys, what strategy can I use to change meshs and materials at runtime? My scenario is this: I have a Corruption Index, and each index (0%, 20%, ..., 100%), I need change my mesh and materials to a different. What approach can I use? Any existing feature at Unity can help me or I need build the in entire logic to do that?

hallow meteor
#

Thanks alot =)

knotty sun
hallow meteor
steady granite
#

Do you guys know a way to know why a GameObject is destroyed? I have OnDestroyed getting called immediately when I start play mode, tried printing StackTrace in OnDestroyed() and OnDisable() but nothing

prime sinew
steady granite
prime sinew
#

is this a singleton..?

#

does it have code in it that destroys itself if there are multiple of it?

steady granite
#

it is a singleton, used to have the destroy if already existing, I removed it but still same result

prime sinew
#

i'd Find All Destroy calls in the project then

steady granite
#

yes, checked it also, no other reference to this object in a destroy call, It looks like it is destroyed from unity itself, like when we change a scene

prime sinew
#

you commented out the Destroy in the singleton part of this?

steady granite
prime sinew
#

not sure then

steady granite
#

one weird thing I just realised, when getting through Awake() for the first time, the instance already has a value no my bad it doesnt

#

Ok, found it, I just didn't add it to my don't destroy onload list πŸ€¦β€β™‚οΈ

trail finch
knotty sun
keen solstice
potent sleet
#

usually it's a coroutine looping through char array aka string

keen solstice
#

thanks

opal cargo
#

Hi guys, any idea how I can rotate my character (Kinematic RB) with a rotating/moving platform it's standing on?

#

Thought about checking if platform has a rigidbody and applying its velocity to my character, but not sure if there is a better way (or this would work at all πŸ˜„ )

severe maple
#

Whenever i add anything to do with normals in shader code (o.Normal = IN.worldNormal), my material turns full black. Any idea why?

potent sleet
#

take notes

opal cargo
potent sleet
#

they got moving platforms

opal cargo
#

Nice, will have a look, thanks!

viral prairie
#
           while (true)
            {
                randPos = new(Random.Range(-rangeX, rangeX), Random.Range(-rangeY, rangeY));
                Collider2D collider = Physics2D.OverlapCircle(randPos, _radius);
                if(collider == null)
                {
                    CreateWell(randPos, _lavaBig, _lavaSmall);
                    break;
                }
            }

Hi, im trying to spread objects randomly on the Area without Collisions, but it always creates them in the Wrong places...
does anyone know a solution?

potent sleet
#

wops wrong reply soz @opal cargo

potent sleet
heady iris
#

that is extremely vague

viral prairie
#

inside of other objects with colliders

primal wind
#

You're not accounting for that in your code

heady iris
#

the overlap check seems reasonable

potent sleet
#

ye

primal wind
#

Oh he is

#

I'm just blind

potent sleet
#

but in this case if you see it inside other objects then make sure colliders are appropriate sizes ?

#

I use usually a CheckBox or CheckSphere for these types of things tho

viral prairie
#

even if it is like 3 times to big, it still appears directly inside others

potent sleet
#

much easier to use boolean

heady iris
#

oh yeah, Physics2D lacks the Check functions

viral prairie
#

its the only one

potent sleet
#

so I'm guessing collider is always null and not finding anything

heady iris
#

are you adding tiles?

#

When you add or remove Tiles on the Tilemap component, the Tilemap Collider 2D updates the Collider shapes during LateUpdate. It batches multiple Tile changes together to ensure minimal impact on performance.

potent sleet
#

oh this is tilemap

#

you might need the World to Cell

#

function

#

physics raycast and tilemap are 2 Different coords

#

worldpos vs gridpos

viral prairie
#

arent these the same if Cellsize is 1?

viral prairie
#

Sadly, delay fixed the problem...

potent sleet
viral prairie
#

Yes i create the Tile-Bulshit in awake, putting the distribution intostart didnt help...

potent sleet
rugged storm
#

I have this if statement that's throwing a null reference exception, what could possible be null here without making one of the !=null false???? wait.. i dont think it could be null... but ill add a test for tilesInMRange to make sure

                if (tInThreatRange != null && tile.Value != null && ally.OccupiedTile != null && tInThreatRange.Contains(tile.Value) && tile.Value != ally.OccupiedTile && !tilesInMRange.Contains(tile.Value))
#

wait it actually might be that lemme test

leaden ice
#

ally could be null

#

tilesInMRange could be bull

#

Lots of options

potent sleet
#

xD that's a big ass if &&

rugged storm
#

I figured it out, in this context ally and tile cant be null due to other stuff it was tilesInMRange

swift falcon
#

ive made an inventory fully from scratch with no tutorial what so ever, can i have some feedback on whats considered "good" and whats considered bad? so i know for in the future

#

it works in the ui and also works without any error so far

potent sleet
#

if it works why worry

#

only refactor if you can no longer manage or read it clear

swift falcon
#

im not worrying, its just im new to unity and i dont know whats considered the standard haha

potent sleet
#

the standard are the usual things, try to stick to SOLID etc.

#

write clean legible code

swift falcon
#

i did this more over to test my skills i cant move on with my game if i have to go to a tutorial on anything i want to implement πŸ˜„

potent sleet
#

avoid repeating yourself ```cs

slotHolder.transform.GetChild(i).GetChild(0).GetComponent<Image>().sprite = null;
slotHolder.transform.GetChild(i).GetChild(0).GetComponent<Image>().enabled```

swift falcon
#

i was thinking about doing something for that but i didnt know what i should do for it

#

any suggestions?

ashen yoke
#

use variables

swift falcon
#

how would i cache that? if you know what i mean

potent sleet
#
var  slotlHolderImage = slotHolder.transform.GetChild(i).GetChild(0).GetComponent<Image>();
swift falcon
#

ah yes

#

this would make it alot better

#

in terms of readability

potent sleet
#

slotlHolderImage.sprite
slotlHolderImage .enabled
etc

potent sleet
swift falcon
#

yup yup

#

ive tried to seperate my code using regions

potent sleet
#

ya regions is good

swift falcon
#

so i can know what group the function belongs to

ashen yoke
#

"avoid repeating yourself" was said to Selfrep

swift falcon
#

πŸ˜‚

ashen yoke
#

regions were a mistake

heady iris
#

i never fold my code

swift falcon
#

the naming of the regions?

#

or just using them in general

heady iris
#

i just ctrl-f to random strings i think are unique in my code

#

- 3f;

potent sleet
#

i usually hide things like Awake for singleton

#

or when you got like 10 props

swift falcon
#

ive also been trying not to populate the Update function with alot of code

#

rather just putting them in seperate functions and calling it from update

heady iris
#

i've done that for one monstrous 2,500 line script

potent sleet
#

I generally avoid Update loop unless i have to

heady iris
#

don't judge me too much

potent sleet
#

i rather use a coroutine as onetime thing

heady iris
#

Senses() calls Sight(), Hearing(), and Touch()

#

i tried splitting the class into partial classes and it was just a nuisance

swift falcon
#

xDDD

heady iris
#

i'm not sure what i'm gonna do about that

#

there's ~just~ enough coupling between different systems to make it non-trivial to split up

swift falcon
#
  void RefreshUI()
    {
        // we loop over our slots
        for (int i = 0; i < slots.Count; i++)
        {
            var slotHolderImage = slotHolder.transform
                .GetChild(i)
                .GetChild(0)
                .GetComponent<Image>();
            // set the image
            if (slots[i].GetItem() != null)
            {
                // TODO: Incorperate Item Amount into this
                slotHolderImage.sprite = slots[i].GetItem().ItemIcon;
                slotHolderImage.enabled = true;
            }
            else
            {
                // get slotpanel  -> get image from slot panel
                slotHolderImage.sprite = null;
                slotHolderImage.enabled = false;
            }
        }
    }
potent sleet
#

unpopular : I've yet to find partial classes useful in unity

swift falcon
#

looks alot cleaner now

heady iris
#

maybe it's just OK that my complex enemy AI script is complicated

ashen yoke
#

nothing just use proper nav

#

there is search by methods, there are hotkeys to jump to the top bar with class/method nav

swift falcon
#

what i normally do is just collapse all of the other regions when im working on a specific region/s

heady iris
#

i like cmd-shift-o in VSCode

#

it searches for symbols in the current file

#

cmd-t is the entire solution, and isn't as fast

#

of course, what i do in practice is start scrolling to find something

#

then i keep doing it because of the sunk cost fallacy

ashen yoke
#

you use vs?

swift falcon
#

who doesnt use vs tbf

ashen yoke
#

those who use rider

swift falcon
#

ngl never heard of it

heady iris
#

vscode, not vs

ashen yoke
#

yikes

hexed pecan
#

VSCode gang

ashen yoke
#

im now looking down on you both

heady iris
swift falcon
heady iris
#

i simply yell at my computer until it works

swift falcon
#

ignore the sprites πŸ˜‚ i couldnt find anything quick

heady iris
swift falcon
#

πŸ˜‚ i had no onhand sprites to use so i just started searching from the ones i imported a little while ago πŸ˜‚

#

more or less the biggest thing i get stuck on isnt the code its self (unless its decently complicated) its the logic behind the script

potent sleet
#

yeah that's the important stuff is logic not the actual code

tardy mortar
potent sleet
#

lol

swift falcon
#

πŸ˜‚

tardy mortar
#

I don't even know where that is from

#

xD

#

but there is a family of them here

potent sleet
swift falcon
#

just because u can write it doesnt mean u understand it

potent sleet
#

eg GPT

swift falcon
#

i watched a video earlier when i was trying to search up some tutorials on some stuff and it was about how watching tutorials will poisen your learning progress (ironic)

#

this one

#

and it made me realize that what hes saying is actually very true so im trying to shift away from tutorials as much as possible

tardy mortar
#

tbh I agree
I found myself doing so many errors at first because all the tutorials try to make it simple for new people but just makes new people learning bad ways of doing what they want xd

potent sleet
#

but this can lead to further curiosities on how it actually works and do self-researching

swift falcon
potent sleet
swift falcon
#

its an eye opener because when i scroll to comments alot of people will just post there errors there ask how to fix which in my eyes means they just copy and pasted it without knowing how it actually works

potent sleet
#

yes and or sometimes bad oversight from tutorial content creator

#

I hate tutorials that post with errors in code/logic without omitting those
I haven't released a vid unless I know there are no actual syntax errors, or any flaws like that. I just redo the whole video from scratch, not even edit

swift falcon
potent sleet
#

this is assuming it's a good tutorial

#

like Seb Lague or alike

swift falcon
#

some tutorials will just tell you what to do without explaining how it works

potent sleet
#

yeah skip those

heady iris
#

i've used very few tutorials

#

i just kinda worked out how to make stuff happen

potent sleet
#

the older unity ones are lokey hidden gems

swift falcon
#

for me its like i know how to do it sometimes its just idk if im doing it the right way, the way that wont cause bugs but however that is apart of learning ig

#

think ive watched a few of his videos tbf when browsing YT

#

does he do ML?

potent sleet
#

he might , haven't checked his stuff in a while

swift falcon
#

he has 1 video on ML in his playlist

potent sleet
#

there a few around that are decent too

#

most of them are devlogs

#

cause you know...hard work aint free lol

glossy wave
#

hello! does this ring any bells in how would i implement a functionality like this picture describes? (this is a pretty useless exercise that i am tasked with doing)

swift falcon
#

Yeah haha, tbf it might be worth me documenting my progress with devlogs on my game

#

Anyways i sleep for now

leaden ice
rugged storm
#

This is always returning with a count of 0 not sure why

 
public List<Tile> GetAllTilesInRange(Vector2Int pos, float maxrange, float minrange)
    {

        return tiles.Values.Where(t => Vector2.Distance(t.Pos, pos) <= maxrange-.5 && Vector2Int.Distance(t.Pos, pos) >= minrange+.5).ToList();
    }
glossy wave
glossy wave
#

ok, i will try this with a 2d collider

desert shard
mild plume
#

My mouse and all input freezes when running this:

using System.Collections.Generic;
using UnityEngine;

public class CharMovement : MonoBehaviour

{
    public float playerSpeed = 50.0f;
    public float rotateSpeed = 100.0f;
    // Start is called before the first frame update
    void Start(){}
    void mouselock(){

    }
    // Update is called once per frame
    void Update()
    {
        
        if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}
        if(Input.GetKeyDown(KeyCode.Mouse0)){Cursor.lockState=CursorLockMode.Locked;}
        while(Cursor.lockState==CursorLockMode.Locked){
            float forbac = Input.GetAxis("Vertical") * playerSpeed * Time.deltaTime;
            float lefrig = Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;
            float rotation = Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime;
            transform.Translate(lefrig, 0, forbac);
            transform.Rotate(0, rotation, 0);
        }
    }
}```
leaden ice
#

replace while with if

mild plume
#

so i can't use while in the update method?

leaden ice
#

you can use while anywhere you want

#

you can't use while when the condition will never become false

#

or you have an infinite loop

#

such as here

#

look inside that loop. The entirety of the game engine and all your code will not continue doing anything until your loop finishes executing.

There is nothing inside the loop that can ever change Cursor.lockState. Since it can't change inside the loop - you will be stuck in the loop forver

#

hence - Unity frozen

mild plume
#

Ah

leaden ice
#

Update runs once per frame. Seems like all you want to do is run that code once per frame while the cursor is locked.

A simple if is sufficient.

mild plume
#

So it also won't work if i put this in the while loop because it never updates to check it? if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}

leaden ice
#

when you put a while loop in, the loop runs to completion instantly

#

the game engine is not going to continue in the meantime

#

it's waiting for your code to finish

#

before it can move to the next frame

#

That's the whole point of Update

#

it runs from top to bottom once every frame

mild plume
#

And it never will because it can't register the escape input

#

Thank you

leaden ice
#

it never even gets a chance to check - because you're stuck in the loop

mild plume
#

Yep, thanks

#

Seems obvious now

heady iris
#

it's a common misconception that stuff happens "at the same time"

#

there is one main thread, and we all have to share it

#

(preemptive multitasking would be when mom says it's your turn on the thread, but that doesn't happen here)

late lion
lime widget
#

I made a game using tilemap. When I play the game everything is looking right. When I sent it to my friends to play, they have the right and left side cropped and can't see the walls. Found out it's because they use other resolution than mine (1920x1080). How can I make everything fit in the screen, including the whole tilemap? I know that i can anchor the ui but that doesn't solve the whole tilemap not fitting

granite nimbus
#

is there a more convenient way of making Dictionary appear in inspector than doing an array of [Serializable] structs with 2 fields and then converting to Dictionary in code?

hard estuary
mild plume
#

Why does this give an error? I want to reference a static method inside MouseLock class, the object (CodeCube) has the 2 components

#

MouseLock.cs

using System.Collections.Generic;
using UnityEngine;

static public class MouseLock
{
    static public void MouseLockMethod()
    {
        // if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}
        if(Input.GetKeyDown(KeyCode.Mouse0)){Cursor.lockState=CursorLockMode.Locked;}
    }
}
hard estuary
lime widget
mild plume
#
using System.Collections.Generic;
using UnityEngine;


public class Main : MonoBehaviour
{
    
    // Start is called before the first frame update
    void Start()
    {
        CodeCube.GetComponent<MouseLock>();
    }

    // Update is called once per frame
    void Update()
    {
        MouseLock.MouseLockMethod();
    }
}
``` CodeCube does not exist in current context
hard estuary
mild plume
#

How can i declare CodeCube? It's an 3d cube object with the 2 C# components

heady iris
#

the name of any objects in your scene is irrelevant: that type does not exist

#

are you trying to find a game object named CodeCube?

mild plume
#

Can i reference other C# scripts without it being a component of an object

heady iris
#

sure, declare a field of type MouseLock on Main

#

e.g. public MouseLock mouseLock;

#

drag the "CodeCube" object into that field

#

you'll get a reference to its MouseLock component

#

you can't just type the name of a game object in C# and wind up with the object

gilded bramble
#

I need help. So I have scene changer and it should work but it doesn't. Here is the script :
using UnityEngine;
using UnityEngine.SceneManagement;
using Photon.Pun;

public class SceneSwitcher : MonoBehaviour
{
public string sceneName;

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("HandTag"))
    {
        SceneManager.LoadScene(sceneName);

        if (PhotonNetwork.InRoom)
            PhotonNetwork.LeaveRoom();
    }
}

}

Yes I have added my scene to Build Settings and it is still not working. Can somebody help me?

mild plume
heady iris
#

you declared a MouseLock class

#

mouseLock is the name of the variable. it can be anything.

mild plume
heady iris
#

yes

#

presumably

#

since you have a component called "Mouse Lock"

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

static public class MouseLock
{
    static public void MouseLockMethod()
    {
        // if(Input.GetKeyDown(KeyCode.Escape)){Cursor.lockState=CursorLockMode.None;}
        if(Input.GetKeyDown(KeyCode.Mouse0)){Cursor.lockState=CursorLockMode.Locked;}
    }
}
heady iris
#

did you create a C# script and then edit it afterwards?

mild plume
#

So with mouselock i can use the method

heady iris
#

this used to be a component

heady iris
#

which is also what this code is trying to do

#

CodeCube.GetComponent<MouseLock>();

#

well, MouseLock is now a static class, and doesn't derive from MonoBehaviour

#

so it is no longer a valid component

#

if you want MouseLock to be a static class, then this will be fine, I guess. You can write MouseLock.MouseLockMethod() to call the method.

meager sky
#

Anyone know a good way to display AudioSource.time as an actual time value?
Building a small audio-player in my game and want to display the actual timestamp values for a songs progress, but running into this issue.

Should display 0:71 as 1:11 instead.

heady iris
#

you will have to remove the component from the cube in your scene, because it's no longer a valid component

mild plume
heady iris
#

no, because mouselock is neither the name of a type nor the name of a variable

#

there is no such thing as mouselock

mild plume
heady iris
#

that would be mouseLock. it's also irrelevant now that I see that MouseLock is a static class

prime sinew
heady iris
#

i thought it was a component, because you showed a screenshot of it being a component

mild plume
#

Yeah i thought it needed to be a component

heady iris
#

if it's just going to be a static class, then you don't need to (and can't) put it in a variable

mild plume
#

That's why i attached it to the CodeCube

heady iris
#

so, just MouseLock.SomeMethod();

meager sky
mild plume
#

And if the MouseLock.cs is in a different directory how do i reference it? how does it know where MouseLock class is?

prime sinew
# mild plume And if the MouseLock.cs is in a different directory how do i reference it? how d...

A few basic ways to get references in Unity.

Directly-
GetComponent 0:38
/GetComponentInChildren
/GetComponentInParent

Public Variable- 3:00

Find- 5:01
Find 5:39 (by name)
FindWithTag 6:14 (by tag)
FindObjectOfType 6:51 (by component)

Interaction- 7:15
OnCollisionEnter
/OnTriggerEnter

β–Ά Play video
#

you should start with some Unity basics

#

check out Unity Learn

mild plume
#

thanks

heady iris
#

yes

shy spire
#

Is there a way to change the opacity/alpha of a colour without having to re-reference the original colour? Something like "color.a = x" instead of having to declare "new Color(r, g, b, a)" again

heady iris
#

you sound very unclear on the basics

#

!learn

tawny elkBOT
#

πŸ§‘β€πŸ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

shy spire
#

Damn, I was hoping I just missed it all this time, thanks

heady iris
#

what? of course you can

#

you just can't do it if the color was returned from a method or property

#

since it's a struct, which means it's a value type

#

so you'd be changing a copy, which would do nothing

#

it's why you can't do transform.position.y += 1

#

you can totally just do

Color x = new Color(1, 0, 0, 1);
x.g = 1;
twin vector
#

Is there any article / youtube clip which I can watch/read that will help me to structure scripts inside the project better? Any help would be great 🍻

hexed pecan
twin vector
simple egret
#

And namespaces! They're nice to separate sections of project

heady iris
#

namespacing your project well sounds like a good way to figure out how you'll do assembly definitions down the road

verbal oxide
#

ive got a 2d isometric grid and i want the camera to be able to rotate around the grid to see it at 4 different angles. with an isometric setup is it easier to change the cameras rotation or do you have to rotate the grid and everything on it, havent had much luck figuring out how to rotate the camera around the grid

leaden ice
verbal oxide
#

cool, that makes sense to me and will attempt that. thanks. i have objects on the grid will those all need to be children of the grid im assuming

heady iris
#

yeah, using empties makes things a lot easier

#

put the empty at the center of the grid and then spin it around the y axis

#

hey, that just gave me an idea for a strategy game

#

the camera rotates 90 degrees every turn, and only visible units can act or be targeted

rugged storm
#

This is always returning with a count of 0 any clues why?

 
public List<Tile> GetAllTilesInRange(Vector2Int pos, float maxrange, float minrange)
    {

        return tiles.Values.Where(t => Vector2.Distance(t.Pos, pos) <= maxrange-.5 && Vector2Int.Distance(t.Pos, pos) >= minrange+.5).ToList();
    }
heady iris
#

are you doing something like GetAllTilesInRange(pos, 3, 5)

#

i'd expect min, then max

rugged storm
#

Oh

heady iris
#

that would cause you to get no results

simple egret
#

Ez fix for future-proofing

if (max < min)
  (min, max) = (max, min); // swap!
rugged storm
#

Ty chem always coming in to help my inability to properly process < > statements

heady iris
#

the statements themselves were fine

#

it was just an unintuitive argument order

#

you shouldn't need to change the implementation

rugged storm
#

πŸ‘Œ

rugged storm
heady iris
#

maybe throw in an assert

#

just so that you'll catch it sooner if it happens again :p

jagged hedge
#

When building my game in dev mode and running it, I'm getting this error seemingly every Update tick
Anyone know what could be going on? It's not appearing in normal unity play mode and seems to be from the Debug Handler itself (so it shouldn't really be a problem but it's still clogging my log files)

jagged hedge
#

Sure

orchid surge
#

Does anyone know how to do GUI.RenderTextureWithTexCoords() with the Graphics class like if Graphics.RenderTextureWithTexCoords() existed (which it doesnt). I have a 9slicing function that relies on IMGUI for this, but I want to draw it on a RenderTexture which I don't think IMGUI can do, so I need to figure out how to do this with the Graphics class.

Graphics does have built in 9slicing, but it relies on stretching instead of tiling, so I can't use it.

placid summit
#

I am interested in ECS Vs OOP but seems Unity's own ECS might be a bit new & complicated in its desire for speed. Has anyone used other ECS frameworks?

hard sparrow
#
    {

        HashSet<Cell> area = new();
        Debug.Log($"area first: {area.Count}");
        foreach (Vector3Int relativeNeighborCubicPosition in HexMath.RelativeNeighborCubicPositions)
        {
            Vector3Int neighborPosition = centerCoordinate + relativeNeighborCubicPosition * radius;
            if (GetCell(neighborPosition, out Cell cell)) area.Add(cell);
            for (int r = 1; r < radius; r++)
            {
                neighborPosition += HexMath.RelativeNeighborCubicPositions[(r+3)%6];
                if (GetCell(neighborPosition, out Cell c)) area.Add(c);
            }
        }
        Debug.Log($"area: {area.Count}");
        return area;
    }```
The first debug is being called but not the second debug. No exceptions are being thrown (just, no area is being returned apparently)
#

how in the world is that possible

heady iris
#

h m m m

#

unity isn't crashing, right?

simple egret
#

Yep that's not possible. Nothing can exit out of the loop early, except an exception being thrown

heady iris
#

it could happen if you had a try-catch wrapping it

#

silently discarding the exception

vale spade
#

not sure if this is the right place, but how do i add this third scene to my hierarchy?

heady iris
#

just drag it in from the Project window

#

that will additively load the scene

#

i'm fuzzy on how that works after that, though

#

i really need to learn more about additive scenes

ashen yoke
#

just keeps it loaded until you rightclick > unload

vale spade
#

yes thats it!

#

thanks!

heady iris
#

does that mean that it'll always be additively loaded in the scene you added it to?

#

i've only ever done it by accident lmao

hard sparrow
#

So the code works fine (both debugs call) when all the cells are present (GetCell == true), but if any one of the GetCell returns false, then the second debug never calls

vale spade
#

I think they kinda co-exists

hard sparrow
#

but I can keep playing and there ae no exceptions

#

Which might be because the method is being called as part of an .OnComplete on a Tween

vale spade
#

I kinda fucked up my entire project 2 days ago when i tried to put every thing on git for safety but ended up deleting my entire project with git reset --hard

heady iris
#

darn, that'd be kinda cool

ashen yoke
#

scene is added to scene stage/context

#

it is cool because you can do exactly that on runtime

heady iris
#

right

#

it'd just be nice to not have difference between "i did it in the editor" and "i did it in the player"

ashen yoke
#

create a scene composition, for example dump all your systems in one scene, then load the content scene additively

#

even better you can avoid doing all the usual singletons/prefabs in work scenes mumbo-jumbo if you hook the editor to first load the scene with your systems then the scene that was just opened

simple egret
heady iris
#

not quite following the "hook the editor" part

hard sparrow
#

hmm... still nothing

simple egret
#

No, try/catch inside OnComplete( [[ HERE ]] )

#

Make that a bodied lambda

#
.OnComplete(() => { try ... catch })
ashen yoke
#

couple key apis

heady iris
#

hm, I will have to look into that!

#

looks scary

#

i've liked the idea of having a "systems" scene

ashen yoke
#

in

PlayModeStateChange.ExitingEditMode

you override the scenes that will be loaded, you grab which one is opened now, then load your systems, and the one that was opened additively

hard sparrow
#

probably the modular is being weird or something

simple egret
#

Ah there we go, so DOTween indeed swallows exceptions, might want to disable its "safe mode" or whatever it's called. If that's even related to exception swallowing

ashen yoke
#

yes there is an option for that i think

simple egret
#

Now that I see the exception, looks like it's thrown in GetCell, which shouldn't be throwing when you pass something out of range, it should return false instead

ashen yoke
#

right its "safe mode"

#

safe mode swallows, without rethrows or skips

#

also in options set logging to verbose

simple egret
#

Like other methods that implement this "TryX" pattern, int.TryParse(string, out int), yours should be called TryGetCell

heady iris
#

ah, that would do it

hard sparrow
#

yes, it's this. If there's no such key then it complains

#

kind of annoying dealing with null cases with structs

simple egret
#

Yeah the first line will throw if the key isn't there

#

You can just do return _bla.TryGetValue(cubicPosition, out cell)

#

(yes I was lazy typing the dictionary name)

hard sparrow
#

sigh... XD

simple egret
#

Surely Rider has a bulk-rename feature

hard sparrow
#

Oh, this just works.

#

how?

#

it auto assigns cell I guess

#

But yes, everything works now

simple egret
#

TryGetValue internally does, yes. It's populated before TryGetValue returns, so it's valid code

ashen yoke
#

you cant compile if the parameter marked as out is not assigned

simple egret
#

TryGetValue sets the out param
GetCell sets the out param
TryGetValue returns
GetCell returns
^ Order of execution

heady iris
#

indeed

#

i did something similar a few days ago

#

it felt very pleasant

hard sparrow
#

There's actually a ton of return statements I refactor to use that

loud stratus
#

Hey, guys! I have a problem. I want to make in my game the highscore to be saved on restart game and whenever I click a difficulty button. Is it somehow possible to do that?

#
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        Debug.Log("The restart button works");
    }``` 
I have the restart game method right here and that's what I do in that.

I have also this method setdifficulty for the player to interact with the game difficulty 

```void SetDifficulty()
    {
        Debug.Log(gameObject.name + " was clicked");
        gameManager.StartGame(difficulty);

    }```
#

I am about to work with playerprefs but don't know where to use them

vale spade
#

i would start with the dont destroy on load. You can make data game object that isnt destroyed on load, and get ur data from there

loud stratus
#

What is the other option you ve suggested?

vale spade
regal epoch
#

hey im having problem with my unity project. i wanted to add ads, and somehow f'ed it up completely. tried restarting unity only to get a compilation error and suggesting to start in safe mode. What are the ads folder names? Ill delete them to get a fresh start

leaden ice
#

and fix your compile errors if they're in your files.

regal epoch
#

i did that multiple times but somehow it doesn't fix the errors

leaden ice
#

did what?

regal epoch
#

uninstalling the packages

leaden ice
#

how did you do it multiple times?

#

Does that mean you reinstalled it?

regal epoch
#

yes

leaden ice
#

unisntall it and leave it uninstalled

#

then go through your compile errors one by one.

regal epoch
#

i'll try that

#

so right now its trying to resolve the android dependencies. i've had it before but it just gets stuck at 0%

lapis galleon
#

Hello, I could really use some help

#
Your script should either check if it is null or you should not destroy the object.```
#

I can see the line where it happens on and I tried to put an if (gameObject != null) block around it, but now the check for gameObject != null is throwing that error

heady iris
#

that would imply that the component itself got destroyed

#

i forget exactly when that triggers an error

#

show your code

#

!code

tawny elkBOT
#
Posting code

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

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

lapis galleon
#

just to explain what is happening, I have a single common scene and then I am loading and unloading additional scenes additively

#

with transitions between them

#

when I go through scenes in order from the beginning when starting the app, everything works perfectly

leaden ice
#

but

#

more likely you want to fix the underlying problem

#

explaining which line this happens on (and perhaps providing the stack trace) would be helpfulk

lapis galleon
#

yeah I do want to fix the underlying problem but for now I want to try to make things better

leaden ice
#

the script you linked seems not to be the problem

#

it's in some other script which has a reference to an instance of this one

#

fixing the underlying problem will make things better

#

adding a null check will just cause unnecessary waste to go unnoticed

#

and possibly give you very hard to debug behavior issues in your code.

lapis galleon
#

yes I do need to fix the underlying problem

#

it's just that I wrote this code over a year ago, and I don't remember everything I did

#

actually maybe I should share the github link

golden vessel
#

Hey, I installed a custom package some time ago and it worked great, but for some reason I now have compilation errors saying I'm missing a namespace. Any idea why that would happen?

#

I don't have any errors in the editor tho only in MVS

leaden ice
golden vessel
lapis galleon
#

I am going to fix the underlying issue, I know it is with the transition engine

#

I've created this complicated thing and need to figure out how it works again and it throwing errors is just making things worse by causing other unrelated problems

golden vessel
#

Is there a in built way I can draw a shape, like the LineRenderer but filled?

leaden ice
golden vessel
leaden ice
#

FIll it?

golden vessel
leaden ice
#

what kind of end result are you looking for here? A mesh? An image / sprite?

#

LineRenderer renders lines, that's all it does

golden vessel
#

Like I would in Illustrator

leaden ice
#

WHy not do it in Illustrator?

golden vessel
#

Cos I can animate it :p

#

Could be cool to have a coroutine adding each points

leaden ice
#

What you're talking about is possible in various ways - but LineRenderer isn't one of them

golden vessel
#

So what are the possibilities?

#

Shaders is one I guess

#

I'm quite illiterate in shaders tho

leaden ice
#

well it's kind of unclear to me still what you mean by "fill"- but yes:

  • a mesh with vertex shaders
  • a mesh actually being modified at runtime
  • a SpriteRenderer rendering a texture that you modify
#

LineRenderer can of course also be animated but it cannot be "filled"

#

it can only draw lines

leaden ice
lapis galleon
#

ok so now that I have that check in there for null I think I can tell what the problem is

#

I don't know yet why it is happening but I know what the problem is

#

I think I'm going to leave that in there but I'm going to keep my log warning for if it is null what to do

#

so that way I can tell if this happens

golden vessel
#

The idea was to do a Yin-yang, and draw another in each tiny circle, zoom infinitely, and there wouldn't be default cos the symbol is always the same "definition"

lapis galleon
#

before it was throwing so many errors it was very hard to tell what was happening

#

now with this check all of the errors are gone, and it behaves better but still not perfect, but I can see my log warning from where it goes wrong

golden vessel
#

Thanks for the info I'll look into it

grim copper
#

this might be silly but this error is so confusing to me

#
    public Volume postProcessVolume;
    private ChromaticAberration chromaticAberration;
    private Vignette vignette;
    private Grain grain;
    private LensDistortion lensDistortion;```
#

The type or namespace name 'Volume' could not be found (are you missing a using directive or an assembly reference?)

#

i am using URP

leaden ice
#

You're missing a using directive or an assembly reference

grim copper
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Rendering.PostProcessing;```
#

nevermind

#

i needed this

using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

leaden ice
#

Yes exactly

#

You were missing a using directive

grim copper
#

alright

#

i've recently switched over to urp so this is all new to me

#

although another error when i press play

#
    {
        transform.position = respawnPoint.position;
        PlayerHealth = startingHealth;
        respawnPoint = transform;
        deathText.enabled = false;
        deathText2.enabled = false;

        // Get post-processing effects from the volume
        postProcessVolume.profile.TryGet(out chromaticAberration);
        postProcessVolume.profile.TryGet(out vignette);
        postProcessVolume.profile.TryGet(out grain);
        postProcessVolume.profile.TryGet(out lensDistortion);
    }```

postProcessVolume.profile.TryGet(out chromaticAberration); is apparently Object reference not set to an instance of an object
#

that entire thing doesn't seem to work

heady iris
#

well, then profile is null

grim copper
#

oh

#

how would i go about fixing that?

#

the script worked before i went to urp

rain crater
#

Hey, I have an issue with my script. It looks like my scripts for generating a mesh along a curve get wrong points (despite them being assigned correctly). It gets fixed when I select either the gameobject with the point or gameobject with the scripts.
This is what I get after I generate the entire mesh.

#

And this is what I get after I just select the mentioned gameobjects, and regenerate the mesh along that curve (this is correct)

#

The way it works, is Intersection.GenerateIntersection() -> LinePlacement.GenerateAlongPath() -> VerticesCollider.GenerateMesh()
(the last function call is not there, but i've added it after realizing it's gone, so it works, but the issue above remains)

rain crater
#

Apparently it happens in any case, where the PathPoint needs to be inverted (that is, swapped tangent ends). And it looks like just selecting the gameobject with the Path script, or specific points, then regenerating, fixes it

lapis galleon
#

@leaden ice FYI, I solved the underlying problem

#

the problem was actually in the code that I pasted

#

I wasn't unregistering the event manager on destroy

#

so upon reloading a scene that was previously loaded, two copies of the script were being triggered, the one for the open copy and the one for the previously opened copy

#

I added an ondestroy function to remove it from the event manager when it was destroyed

fresh heron
#

Hello! I have a class that loads and transitions scenes and fire events like such:

public class SceneLoader {
    private static event UnityAction SceneLoadedEvent;
    private static void OnSceneLoadedEvent() => SceneLoadedEvent?.Invoke();
}

I would like to subscribe to the SceneLoadedEvent from other classes without giving public access.
My understanding of C# events is weak, no matter how much documentation I read on it.

Ideally I could subscribe from another class like:

public class UI_LevelLoad {
    private void OnEnable()
    {
        SceneLoader.SceneLoadedEvent_Subscribe(ShowUI, true);
    }

    private void OnDisable(){
        SceneLoader.SceneLoadedEvent_Subscribe(ShowUI, false);
    }

    private void ShowUI(){

    }
}
analog relic
fresh heron
#

Jeez

#

I was totally overthinking this

regal epoch
#

im fighting with my unity app and almost throwing my pc out. its not letting me patch and run to my phone like it did before. the error log tells me the "APK is out of sync". Can't find anything about it online.

#

a bit further down the error it says "this feature requires ASM7"

#

nvm i changed the target api and it works again

swift falcon
#

Does anyone at least know more or less how the CharacterController.Move function works?

#

I don't want to use the built-in CharacterController component, instead opting for my own custom character controller.

heady iris
#

although, actually, that doesn't work for non-convex mesh colliders

#

and the docs mention that

One particular example is an implementation of a character controller where a specific reaction to collision with the surrounding physics objects is required

#

whilst character controllers don't really have a ... specific reaction

#

feels more like a capsule cast

swift falcon
heady iris
#

the movement itself should be pretty trivial

#

if you don't hit anything, you just...move by the amount specified

#

the interesting part of a character controller is how it deals with collisions

#

it must be more than just a capsule cast, given how character controllers can climb up slopes and over ledges

swift falcon
#

πŸ€”

heady iris
#

right

#

a character controller is not a rigidbody

#

it is not affected by physics

swift falcon
#

Maybe it's detecting collision and then performing a direct transform.position manipulation?

heady iris
#

it merely respects collisions

void basalt
#

If it moves into something, all it's going to do is move out of it

#

If you actually want to understand the underlying collision detection & resolution, then this is probably a good place to start

swift falcon
#

Again, I'm not as interested in the collision... yet.

I was looking more for how it actually moves the player. If it happens to be a direct transform.position change, then I'll likely need to look into the collision schema again.

void basalt
#

I don't have access to unity's source code, but if I had to speculate, it probably isn't performing a real transform update twice

#

it's just logically updating the collider data and then performing the resolution against that using something like the first link I sent

#

after the resolution is done, is probably when the actual gameobjects get updated

#

HST is pretty straightforward. It's just projecting the bounding box onto the normal axes of both potentially colliding objects

#

if there's a gap of any size between them, they aren't colliding.

#

but obviously you won't be writing your own HST. Physics.ComputePenetration is more than enough.

leaden ice
foggy pasture
#

would anyone have some advice for how to resolve overlapping shadows like this?

#

i was thinking about just doing it through a shader on the sprite material but wasn't sure

#

unsure what'd be most performant given the high number of trees/etc.

deep willow
#

im using navmesh to move agent objects, but they jitter sometimes. it seems to only happen when i instantiate a new agent object and that object's destiantion is set to the same destination as another agent object. How do i stop the jittering?

#

i guess they're jittering becuase they never reach the destination

swift falcon
winged sphinx
#

do I have to worry about injection when using unity's input field?

leaden ice
#

E.g. plugging it into a SQL query

swift falcon
#

https://gdl.space/okurofeqej.cs
could anyone maybe look through this code and spot anything im doing the wrong way? it all works but i wrote without any help or anything i tried to explain my logic through comments so i didnt get side tracked

#

i had to rewrite the refresh hotbar a few times thats why its heavily commented

void basalt
swift falcon
#

Or failing to substitute properly.

void basalt
#

what

#

that is so random dude

swift falcon
#

Unity only provides an extern reference to the move function, meaning it's a function handled externally.

swift falcon
#

I assume this is the PhysX library they use.

void basalt
#

I've already explained to you how controllers work internally

#

nvidia isn't going to do some 180 backwards shit

swift falcon
#

switch to vscode πŸ‘€ imo its better

#

Capsule cast + move?

void basalt
#

no

#

depenetration is how character controllers are written

swift falcon
#

This jargon is currently meaningless to me. I'm looking for code, not concepts. I want to see the code behind it so I can see it in practice.

void basalt
#

here you go

swift falcon
#

I can't see it in-game currently because the collider generated by the CharacterController is causing all sorts of issues.

#

Yes, you posted that already.

#

I was going to look into that next.

void basalt
#

So like

#

why dont you just write your own controller

#

using unity's method I showed you earlier

#

@swift falconLooks like I was half-wrong. Looks like Nvidia does sweeptests and depenetration

swift falcon
#

I might... after I understand how the movement code I acquired is actually supposed to work.

void basalt
#

The native code is going to be in C++

#

all backend engine code is in C++

swift falcon
#

Remember, I have code I'm borrowing.

swift falcon
void basalt
#

I don't understand what borrowing code means

swift falcon
#

Someone else wrote the code.

#

It's code that faithfully recreates "CPMA-style" movement in Unity.

#

The only thing is that it takes all of that movement calculation and puts it into a single Vector3, which is then passed to the CharacterController.Move function, in that code.

#

My own controller uses a Rigidbody component and calls AddForce to propel the player.

void basalt
#

You should absolutely not be using rigidbodies and character controllers on the same object.

swift falcon
#

So currently the movement is not working as it should.

swift falcon
#

But now the numbers are all off.

void basalt
#

is CPMA doom?

swift falcon
#

Because if I'm jumping and moving, I'm gonna be accruing plenty of speed.

swift falcon
void basalt
#

Yeah, none of this warrants looking at the backend code

#

you can do everything you've explained above with a character controller. There's nothing stopping you

swift falcon
#

Not with Unity's, I'd have to make my own somehow.

void basalt
#

but why????

swift falcon
#

The collider it generates interferes with plenty of things.

#

Especially the projectiles fired from my weapons.

void basalt
#

so then place individual collider triggers on each of its limbs lmfao

#

you're trying to make this too complicated

#

tell me what else it interferes with

swift falcon
#

I don't seem to be able to jump.

#

However I'm not sure if that's due to improperly implemented code or the collider.

void basalt
#

I can assure you the character controller jumps fine

#

if the correct logic is written on top of it

#

me and millions of other people have done it

#

for the character hitbox, just put trigger colliders parented to each of the limbs

#

it's that easy

#

you can put your character controller on a separate layer and have your bullets ignore it

rose token
#

I'm making a unity 2D game with ragdoll physics. The game revolves around a stickman which is able to aim weapons, where the weapons rotate towards the mouse position. An example issue I'm facing when aiming a weapon is that if the mouse is quickly moved from the right, then over the player ending in the left side of the screen, the player's rotation will be calculated wrong, resulting in the players arms being bent, no longer following the mouse correctly. How can this issue be resolved?

Attached is a video demonstrating the issue, as my articulate skills are not the best
For more information feel free to ask
Please @rose token

rose token
#

whoops, sorry

normal cedar
#

Guys, when I try to set position of the player when I have CharacterController I don't get any changes to the my position.

#

What's the problem?

dusk apex
#

CC disables the changes made to Transform.

normal cedar
#

Oh, okay.

#

Nice.

quartz folio
#

Please no reaction gifs.

normal cedar
swift falcon
#

i have 2 items of the same class that hold the variable int amount

how would i calculate the combine amount? say for instance i have 2 items in my inventory the items have a max stack of 5
1 item has the amount of 3 and the other item has the amount of 3 how would i add 3 + 3 and get the remainder?

thin aurora
swift falcon
#

the 2 Slots are seperate and not in a list

thin aurora
#

How does your inventory keep track of the items, then?

swift falcon
#

its hard to explain but what im setting is 2 differnt values of the same list

#

they are cached as SlotClass

thin aurora
#

You should share your code

swift falcon
thin aurora
#

Not much I can do to answer when your setup is different to what I would expect

#

So they're all a SlotClass?

#

What is in that?

swift falcon
#

just data thats stored and methods for that specific slot class e.g item, amount and Constructors

#

ill share the code

thin aurora
#

So if amount is in there, how is my code not a solution?

#

You just need to allow amount to be accessed outside the class using a property, or by making it public

#

You actually already have that, with GetAmount

swift falcon
#

the amount is accessible its exposed in SlotClass

#

yeah

thin aurora
#
var totalAmount = this.items.Sum(x => x.GetAmount());
swift falcon
#

ngl i cant see how it would compare the 2 values

thin aurora
#

You mean there is more to collect?

#

As in, there are more amounts that should add to the sum?

swift falcon
#

moving_slot is cached when clicked on and nearest slot is cached inside the function when a player clicks on an empty slot

#

or on a slot thats stackable

thin aurora
#

Well you could add those to the function if you need them

#
var totalAmount = this.items
  .Concat(new[] { this.moving_slot, this.nearest_slot })
  .Sum(x => x.GetAmount());
#

Unless I'm not understanding correctly

swift falcon
#

i need to find the difference after the value has been added when it reaches a stack of 5 but theres 6 items i need to be able to set the moving slot to 1 as thats the amount thats left

thin aurora
#

I'm not sure what you mean

swift falcon
#

right so if i pickup an item in a slot that has a stack size of 3

i go to place that item in another slot that has 3 but the max stack size for that item is 5 ill have 1 item left over

#

thats what im trying to calculate

lone cape
#

Hi, Instead of using singleton, I'm trying to create a subclass of my GameManager using Inheritance. E.g. ConnectionManager : GameManager The only issue i'm having is that now the ConnectionManager serializes all components from the gamemanager in the inspector. I just want it to serialize its own class. How can i go about doing that? or is my architecture that is flawed from the start?

swift falcon
#

you want to serialize GameManager?

lone cape
#

Yes GameManager has properties i want to serialize but i dont want them shown in connection manager since it should use the same properties

#

I'm starting to think the architecture is flawed and im using inheritence wrong.

swift falcon
#

well If connection manager inherits from GameManager all the serialized variables inside GameManager will show on the inspector anyways on what ever ConnectionManager sits on

lone cape
#

yea the connection manager sits on the gamemanager...i just wanted to split up the code into different classes

#

I also didnt want to make the variables public...so i was using protected.

swift falcon
#

hmmm

#

GameManager is a GameObject?

#

and theres also a class called GameManager?

lone cape
#

yea

swift falcon
#

what do you want to show in the inspector and what do you not want to show in the inspector?

#

if your wanting to use varibles and methods from GameManager but dont want them to be shown in the inspector id just recommend making gamemanager a singleton rather than inherriting from it

lone cape
#

I want the Variables shown in the GameManager class to show in the inspector for the GameManager class only. Then the ConnectionManager can use the GameManager Variables and change them but will only show Its variables in the inspector

#

I guess i should probably use singleton yea...but then it makes the GM public and i didn't really want that.

swift falcon
#

whats wrong with it being public?

lone cape
#

idk potential security risks?

swift falcon
#

are you just reading variables from connection manager?

lone cape
#

its for a multiplayer game and i kinda wanted a lockdown

#

no i think its reading and changing

swift falcon
#

i was going to say use protected readonly field

lone cape
#

Also since I'm using the variables so often its going to be annyoing to put GameManager.Instance.##Variable## every time i use it no?

#

will look very messy

swift falcon
#

can cache it at the top of your file

#

GameManager gm = GameManager.Instance;

lone cape
#

still then need to put gm.#Variable## each time aswell

#

i have like over 100 use cases just in this class...probably alot more in others

swift falcon
#

you can use the [HideInInspector] attribute no?

lone cape
#

but i still want it searilized for GM class

swift falcon
lone cape
#

One sec. If im doing ConnectionManager : GameManager when i change values in Connection Manager...will it change the values in the gamemanager?

swift falcon
#

it will show the base serialized data from GameManager if there is any

lone cape
#

right...yea im doing this wrong

swift falcon
#

for instance i have a scriptable object called item

#

and another that has inheritted from item

#

it will show the base serialized data from item and the data ive also serialized in the other class

lone cape
#

All i want to do really is break down the GameManager class into submanager classes that can use and alter the base variables in gamemanager.

swift falcon
#

could use a namespace

lone cape
#

was thinking that

swift falcon
#

might be your best option tbf

lone cape
#

namespace + singleton you mean?

swift falcon
#

singletons are only accessible when the script has been instantiated

rain crater
#

What methods are called when I select a game object, and how can I call them myself?

rain crater
#

Like, click on the game object in the hierarchy, or just in the scene view. Anything, so it's selected

swift falcon
#

should be this i think

rain crater
#

Hm, doesn't seem like this is what I need, I guess I have to dig deeper. But thanks nevertheless!

swift falcon
#

nws πŸ‘

rain crater
swift falcon
#

ur issue is that the mesh is incorrectly generating or z fighting?

rain crater
#

Incorrectly generating. Although the points given to the script generating it are correct

#

As you can see, it does well for every other part of the road, but not this one.

swift falcon
#

its most likely a code issue then tbf

#

infact

#

if ur editor fixes it when its been selected it cant be

rain crater
#

Ye, that's what I thought

swift falcon
#

hows it look in the game view?

rain crater
#

It seems like, when I select the game object with that script, it does kinda refresh it or something. Or maybe there's some stuff in the OnSceneGUI or OnInspectorGUI (editor for Path script) that I didn't notice.

rain crater
swift falcon
#

are you able to replicate this issue on a different version of the unity editor?

rain crater
swift falcon
#

yeah there could be a bug in the that versions render pipeline

#

i wish my school did game dev :/

rain crater
#

I wish the same, but then I realize how bad are schools in my country at teaching stuff, so it's probably for the better that we don't learn that

swift falcon
#

ah i see, here in the uk well i cant really say anything im 17 and i havent been to school in like 4 years

rain crater
#

Luckily I'm studying at the university already, and here it's better. And we can pick gamedev as specialization later on (probably).

swift falcon
#

ah i see πŸ˜„

rain crater
swift falcon
#

there are some ways to fix tho

rain crater
#

Hm... Those are quite basic. I think probably the most optimal way would be to change how mesh is being rendered, but then that is complicated

#

And since there are other games that do it similarly to how I do it, there's nothing to worry about I think

swift falcon
#

Yeah haha, i dont know much about these kinda things as im just learning myself πŸ˜„

rain crater
#

Understandable, I'm learning that stuff too. But all I can say as of now is that procedural mesh generation is a great thing

rain crater
swift falcon
#

Yeah sure πŸ˜„

tacit nest
#

Hi, I'm making a 1v1 football game and when I move the two characters/objects, they move at the same time. I need someone to help me make a code to control a character with wasd and another with the little arrows.

regal epoch
#

hey im trying to integrate ads in my mobile game. I'm using admob from google. I added my phone as a test device and a banner on the home screen as test. on my pc when i run it i see the banner, but i dont see it on my phone. Anyone an idea?

cosmic rain
regal epoch
#

Im checking right now but it's not giving me any errors. what should i look for in the logs?

cosmic rain
#

If it doesn't, see if you can elevate the verbosity level and rebuild your app.

regal epoch
#

i have it on the highest right now, but cannot see anything about ads

#

what i do see tho thta it's trying to resize something when i press the ad button

#

(it should display a banner when i press the ad button)

main token
#

Are there any github engineers able to help me with my github setup? I'm using git lfs, and for some reason I keep getting files which appear seemingly randomly, then refuse to get discarded. The only way to get rid of these files is to run a series of git commands, only for them to later reappear. thanks in advance

cosmic rain
#

Or you're filtering out the relevant logs

regal epoch
#

i dont think i have any filters on, haven't added them

#

And when i search for "ads" nothing shows up

cosmic rain
#

Also, you said the verbosity is set to high, but what other options are there?

regal epoch
#

there is
verbose(show all)
Debug
info(default)
warning
error
fatal(highest priority)

regal epoch
#

verbose (Show all)

cosmic rain
#

Okay. Then you should be able to see at least some logs, if your setup is correct.

regal epoch
#

well the weird thing is, no i don't see anything that has to do with ads

cosmic rain
regal epoch
cosmic rain
#

Do the "Initialization complete" logs appear in the logcat?

regal epoch
#

nope

cosmic rain
# regal epoch nope

Maybe look into the ads manager script and add some logs of your own to see what's going on. Or even connect a debugger and step through the code.

regal epoch
#

i'll add some logs in the start function, and in the function of the banner. I'll see whay i can ind

granite nimbus
#

I don't understand how you can throw NullReferenceException and point to the line where I check if thing is null
if (myClassInstance != null)
how in the world this line can throw an exceptionπŸ€·β€β™€οΈ

regal epoch
#

tried in multiple scripts but none are showing

cosmic rain
regal epoch
#

I added a debug on the scene change, and even that did not show

cosmic rain
granite nimbus
#

I don't get how an if null check can throw NRE

cosmic rain
cosmic rain
regal epoch
cosmic rain
cosmic rain
granite nimbus
cosmic rain
#

please don't simplify your code when asking a question

#

Here, piecesManager is probably null

granite nimbus
cosmic rain
#

yes

simple egret
#

Errors says otherwise

cosmic rain
#

Otherwise there wouldn't be an error

simple egret
#

It was null at the time this line ran

granite nimbus
cosmic rain
granite nimbus
simple egret
#

wat

cosmic rain
tropic quartz
simple egret
#

Ah, yeah this is never null, hence the difference

cosmic rain
granite nimbus
cosmic rain
#

There's no underlying math here.
Anyways, if you don't need any more help, there's no point in dragging this on.

tropic quartz
#

My head hurts.
Anyway, check for git conflicts if you are using it, had a guy yesterday with an error that made no sense. Was a conflict with git.

I can't really think of what would cause that normally.

#

Or perhaps the thing you are pulling .draggedPiece from is null. That is, piecesManager.

simple egret
#

Nothing, it's just that they generalised and got rid of what could throw such exception when posting here

#

Yeah, the manager was null here

#

a != null can't throw, a.b != null can (assuming a is a field)

granite nimbus
#

ok apparently it was an issue with static fields because of disabled domain reload

cosmic rain
#

Which was making it null.

heady iris
gray mural
#

how do I fix it?
sorry not screenshot, that's better I guess

simple egret
#

Looks like this isn't a UnityEvent, but a regular C# event. There's no AddListener on that, you need to subscribe the C# way:

diff.onClick += () => { /* ... */ }
#

(note that using a lambda, you will not be able to unsubscribe from it)

steady moat
gray mural
sour zealot
cosmic rain
#

It would definitely compile, but it probably wouldn't work the way you intend it to(depending on what you intend though).

sour zealot
#

its a teleporter

gray mural
# gray mural thanks, no errors, I guess it should work now

never mind, now it throws:

InvalidCastException: Specified cast is not valid.
SpawnManager.Start () (at Assets/#Scripts/SpawnManager.cs:37)
private void Start()
    {
        scoreManager = GetComponent<ScoreManager>();

        foreach (Button diff in difficultiesGm.transform)
        {
            diff.clicked += () =>
            {
                Debug.Log("nice");
            };
        }
    }
sour zealot
#

so it teleports the player to the targetTeleporter

cosmic rain
sour zealot
#

and after you teleport, the teleporter goes on a cooldown on both ends

cosmic rain
#

Well, the cooldown part is probably not gonna work

sour zealot
#

oh i know that

#

i need to do that

#

I need it so if the just teleported is true, it will ignore all collisions

simple egret
cosmic rain
sour zealot
#

oh

#

okay

#

il tag u in code begin

gray mural
simple egret
#

NullReferenceException?

gray mural
#

oh, do not mention Destroy error

#
private void Start()
{
    scoreManager = GetComponent<ScoreManager>();

    foreach (Transform diff in difficultiesGm.transform)
    {
        diff.GetComponent<Button>().clicked += () =>
        {
            Debug.Log("nice");
        };
    }
}
simple egret
#

Oh, so that Button you pass in there isn't what you think it is. Do you have your own class named that?

simple egret
#

Hover over it in your code editor, what appears in the tooltip? It should mention the full namespace of that Button type

gray mural
simple egret
#

Yeah it was picking up another Button class, if this works

heady iris
#

you might have a class called Button

gray mural
gray mural
simple egret
#

Ah that'll do it

heady iris
#

ahh

#

yeah

simple egret
#

Also consider using Text Mesh Pro, the UnityEngine.UI stuff is old now

gray mural
#
diff.GetComponent<UnityEngine.UIElements.Button>().clicked += () =>
{
    Debug.Log("nice");
};
heady iris
#

Button still comes from UnityEngine.UI

#

there is no special text mesh pro button component

simple egret
#

Ah, uhh so it's Dropdown that has its own TMP right?

heady iris
#

the "text mesh pro" version in the GameObject menu just uses a TMP text component instead of the legacy one

gray mural
heady iris
#

yeah, there's a special TMP_Dropdown

simple egret
gray mural
simple egret
#

TMP > all

gray mural
heady iris
#

google "discord timestamp"

#

i should add that

simple egret
#

Oh it uses discord's markdown to render a timestamp hang on

#
12:00 PM for me is <t:1641034800:t> for you
heady iris
#

oh right, you can just use that directly

simple egret
#

Basically, first <t: is for MD to recognize it. Then the number is the Unix timestamp of some date, any date as long as it's on 12pm, then the second t is the format specifier for "short time"

heady iris
#

specifically, any time that's 12 PM in your timezone

#

so you'll see 12 PM

steady granite
#

What can make a component's OnEnable() trigger before another component on the same object Awake(), I thought it should be all Awakes in scene, then OnEnable() if component is enabled