#archived-code-general

1 messages · Page 20 of 1

thick socket
#

any way to make sure it actually backs it up to git?

leaden ice
thick socket
#

yessir

leaden ice
#

basically you can just check git status with any other git client

#

but it's unlikely git would be confused

lime vale
#

hello I am working on a dash mechanic and I have it implimanted but I want it so when you dash your keybinds are blocked and you cant change the direction

quaint rock
#

file -> save project in unity

thick socket
#

saving

#

then removing from list

#

and saving

warm night
#

Hey, i have a box collider which is triggered. I want it to collides with the layer "Platform", but not with my player, how can i do that?

leaden ice
balmy schooner
#

Does anyone know how to add bloom effect to a singular game object?

quaint rock
#

its a little complicted but doable

#

more or less need to write that object into its own buffer so the post processing can bloom just it

#

how you do it heavily depends on what you are using render pipeline and post processing wise

warm night
balmy schooner
#

What's a buffer🤣

quaint rock
#

really only a easy thing if you already know how render features work or have wrote post processing effects

balmy schooner
#

I'm basically a fresh beginner at unity, I'm not really sure about any of that, how would I learn about it?

hasty canopy
thick socket
#
item.ID = spriteCollection.Armor.Single(i => i.Name == item.ID).Id;
#

how can I change this so if it doesn't exist it doesn't try to set it

#

Im not great with linq

#

so not sure where to put the ? (everywhere I've tried has thrown errors)

leaden ice
#

what is Armor?

#

what is spriteCollection

thick socket
#

sorry yeah that might be important

#

its a SO with Armor category and this inside it

bold terrace
#

Since TerrrainData cant be serialized/deserialized with newtonsoft json.NET. How else can i save TerrainData so it can be loaded after my game has been quitted and started again?

thick socket
#

I would guess a list....but no source code as its a dll

#
item.ID = spriteCollection.Armor.Single(i => i.Name == item.ID).Id;

want to make the top code do what the bottom does

foreach(var tmpItem in spriteCollection.Armor)
            {
                if(item.ID == tmpItem.Name)
                {
                    item.ID = tmpItem.Id;
                }
            }
strong ravine
#

I've posted this on the Webgl but no one answered so I gonna put it here.

Ok, I can't find what is causing the following bug

https://gdl.space/oniwosikug.cs

lime vale
#

Hello I need help in a dash mechanic, I want it so when it dashes it blocks the keybinds of movement so it dosen't change direction

thick socket
#

and only allow keystrokes when not dash

ember cedar
#

no matter what i change the shooting always happens 90 degrees of, how can i change it so that it shoots towards mouse

#

but im not yet good with angles and rotations in c# so theres probably some stupid bug

orchid bane
#

If I have something like

_event += M1;
_event += M2;

M1() => _event -= M2;
M2() => Debug.Log(1);

Will I never have the debug?

late lion
orchid bane
#

Just tested, somehow both are called

thick socket
potent sleet
# ember cedar no matter what i change the shooting always happens 90 degrees of, how can i cha...

I have covid atm so apologies if i sound odd in this.
Make sure to subscribe for more content!

Main Channel: https://www.youtube.com/c/bblakeyyy

Patreon with fully explained c# scripts:
https://www.patreon.com/BlakeyGames

NEW SERVER LINK: https://discord.gg/cyskvvyDeH

Silhouette Dash free download:
https://blakey-games.itch.io/silhouette-da...

▶ Play video
ember cedar
#

thanks

naive swallow
#

So, I have an algorithm for Levenshtein Distance, that helps me check fuzzy equality, but how would I use it to implement a fuzzy search? Like, if I am searching for the word fnce, how might I get it to find the string barriers_perimiter_outer_fence? It'd find fence since it's close to fnce but there's a lot of extra letters that need to be added and that makes the Levenshtein score drastically drop.

late lion
thick socket
#

there should only be 1 instance...or 0 instances

#

where there were 0 it was erroring which was the issue

orchid bane
#

Idk when I use linq it NEVER works

thick socket
late lion
naive swallow
late lion
thick socket
#

fair enough thanks 🙂

#

figured idk how linq works so there was probably a way to do it in 1 line

naive swallow
late lion
#

But I'm surprised there aren't more libraries for something like this.

naive swallow
#

I'm not sure how to install a separate solution into Unity in a clean way. Do I just drop the whole source folder into the project somewhere? I'd need to make sure that licensing doesn't cause any trouble

late lion
#

It's on NuGet and you can download the package manually, open it as an archive and find the .dll that best matches Unity. In this case it would be netstandard2.0 or netstandard2.1:
https://www.nuget.org/api/v2/package/FuzzySharp/2.0.2 (this link will start the download)

naive swallow
#

I don't really know a lot about licensing I just know that as a blanket rule anything in the package manager is okay

#

I'll see if I can use this one

late lion
#

MIT License on GitHub, so you should be good

#

Should be able to open it in 7-Zip or WinRAR

naive swallow
#

Perfect.

#

I'll probably still have to run it by the higher-ups but if there's no issue with including it I will do that

late lion
#

In that case, the safest option would be to clone the repo and build the DLL yourself, since you can't really guarantee that one hasn't been tampered with.

fresh merlin
#

I have an enemy, facing a direction. I'd like to be able to get the direction of the player, relative to the direction the enemy is facing. How would I go about doing that?

#

I was thinking getting the angle the player is facing and the angle the enemy is facing and getting the sum, but that doesn't work as a reproducible formula

leaden ice
fresh merlin
#

Really? That's it?

#

There's a function for it? yuiCry

hollow osprey
#

How would i go about making a script that choose 1 random animation to play ?

prime sinew
modern creek
#

Remind me again - coroutines can't be started (successfully) in OnEnable (right..?). If I want an animation to start as soon as the object is enabled.. where should I put that code? Do I have to do some silly wait one frame stuff?

prime sinew
modern creek
#

Ah.. I think I know what it is.. maybe? My OnDis/Enable looks like this:

        private void OnEnable()
        {
            StartCoroutine(IsShaking ? StartShaking() : GentleMoveCoroutine());
        }

        private void OnDisable()
        {
            StopAllCoroutines();
            DOTween.Kill(GenericUnityUtils.ShipTweens);
        }

And due to a weird way I'm initializing this object I'm setting it active, inactive, then active again (in the same frame)

#

I'm betting if I stop a coroutine and then try to start it in the same frame, it's failing..?

prime sinew
#

oh. maybe.. all i do know is coroutines stop when the object is disabled

modern creek
#

Yeah, I got that much.. that's how I started down this bughunt - the tween was getting killed from OD and I didn't think I was disabling it

#

but I realized my .. navigation system disables everything then enables the tab I want to view - which was borking up my animations

#

But.. it seems like it should just start again with the subsequent OE

prime sinew
#

I'm afraid you might be more informed than I am on this, so I dont think i can help

modern creek
#

hm I wonder if this is the issue

#

I don't know if StopCoroutine just "marks it as stopped" for later stoppage (in the same frame) or something.. meaning the StartCoroutine wouldn't work

#

Yeah, pretty sure there's weirdness if you start/stop/start a coroutine in the same frame. Just added a flag to Update(), all the coroutines set the flag to true, ondisable sets it to false. Works fine.

quaint rock
#

it takes a handle to a running coroutine, and stops it from running its next iteration

#

though in that code if you are starting coroutines OnEnable and stopping them OnDisable it should not be coroutine

#

you are just recreating a update loop at that point

azure heath
#

Folks, this code only appears to be drawing one red circle (or many overdrawing each other), though it should be drawing a line of them along a list of vector 3s. It's inside OnDrawGizmos.

Handles.color = Color.red;
            for (int i = 0; i < PosHistory.Count; i++)// += 25)
            {
                Debug.Log("Drawing Handle at i: " + i + ", this is position: " + PosHistory[i]);
                Handles.DrawWireDisc(PosHistory[i], -Vector3.forward, 0.1f);
            }

Any ideas?

thick socket
azure heath
#

Yeah, doing that as I iterate through it...

#

(If I understand you correctly!)

stark plaza
#

I have a player object that moves around the map, when over a specific tile I wanna trigger an event. Right now I'm checking every frame like an idiot. What's a good way to handle this? Observer pattern?

modern creek
#

@quaint rock Found the issue, was unrelated to the coroutines at all. DOTween.Flip() does not work correctly or .. as advertised. Lots of debug diving to find that out.

modern creek
#

GentleMove -> StartShaking -> Shaking -> EndShaking -> GentleMove

#

Actually, DOShake has the note I needed but.. Flip() didn't. 😦

#

"no from version"

#

poo.

#

Anyone got any ideas on how to emulate a shake over 3 sec ramping up in vibrato? Short of doing several constant shakes for short durations...

quaint rock
#

just shake it using perlin noise or something similar, while increasing the amplitiude over time

#

would just make my own coroutine to do it, instead of using dotween

charred root
#

any1 know any good scripts for dynamic 2d movement i want something that feels clean

karmic stratus
#

does anyone know why this is giving me a WebException: Error: NameResolutionFailure?

public static class ApiHelper
{
    public static Root GetDefinition()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://wordsapiv1.p.mashape.com/words/hello/definitions");
        request.Headers.Add("X-RapidAPI-Key", "api_key_goes_here_yes_i_tried_with_the_api_key");
        request.Headers.Add("X-RapidAPI-Host", "wordsapiv1.p.rapidapi.com");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string json = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<Root>(json);
    }
}```
prime sinew
karmic stratus
#

does it havbe something to do with my api key?

prime sinew
#

yeah maybe

#

that usually means you can connect, you're just not.. authorized I think

karmic stratus
#

ok i'll look into it :)

thick socket
#

I want to use multiple enum values as a condition

modern creek
#

Sure, make a method that returns true/false on that condition.

[ShowIf("IsFancy")] public int MyFancyInt;

public bool IsFancy()
{
  return x > 1 && y < 5 && up < down && left == right;
}
thick socket
#

hadn't considered that

wary ferry
#

anyone know where I can find info on the diffrent brushes for the tile pallette tool? I'm having a lot of trouble finding things that talk about them

azure heath
eager aspen
#

hi, im working on a system where you have a car, that you can add blocks on to. The Issue is that when I spawn them in (as a child of the car) it messes up the rigidbody. all of a sudden the car wont drive anymore, and Im not really sure why, the blocks just have a box collider (on a layer set not to collide with the car itself) so im not sure how to fix this. any help appreciated.

fervent siren
#

So, via code, say you get an animation clip, and then you getcurvebindings of that clip so you can see the "objects" (aka the binding.path), attempting to set the binding path to another object (or rather, the path of it) doesn't seem to update the animation file. There any way to go about that?

lunar lynx
#

does anyone know how to create a bulk drag/drop field in Unity inspector?
kind of like a public List, except instead of assigning each slot individually, I can just drop all stuff in at once

thick socket
#

but if you lock the inspector

#

you can do that

#

can click like 3 things and drag them all in at once

lunar lynx
#

oh. my. god.

thick socket
#

ikr

lunar lynx
#

i just drag it on top of the list name

#

LOL

#

thank you!

thick socket
#

yeah np!

lunar lynx
#

thanks @thick socket

#

oh it doesnt do the karma thing?

thick socket
#

¯_(ツ)_/¯

lunar lynx
#

🙏

azure heath
eager aspen
thick socket
#

they may have a better idea there if its a rigid body issue

eager aspen
south forge
#

Hey guys, i want the code to realise that its trying to access elements outside of the array and do something in response however im not sure what to place in the condition parameter of my if statement to account for this

thick socket
#

if x > array.size?

#

something like that?

#

or not what you mean

south forge
graceful patio
#

meshes in unity im confuse with 💀
how would the work exactly?

#

are there sperate game Objects for everything and require scripting to stay with the main body of a mess or are there one game object are a sprite

ionic socket
#

Code style question: do you prefer "public T myVar {get; private set;}" or "[SerializeField] T privateVar; public T PrivateVar => privateVar" to provide access to variables in other classes? Is one way explicitly better than the other?

thick socket
ionic socket
graceful patio
#

one question abt meshes if u import a model into unity would the eidtor know what stays seperate vs what doesnt stay seperate

#

do meshes in unity work like this

U have a mesh
u created using blender import the mesh into unity, and the blender file is formated so unity can know the seperate vertices and such.

#

but for the mesh todo stuff u have to add code to each vertice unity detects

#

is that how meshes work?

#

or seperate shape unity detects

#

Idk. I dont do 3D i only know 2D geomtry

south forge
#

i realised i keep getting errors because im trying to get the index but that index that doesnt exist lol

#

is there a way to say if this is equal to null but for if the integer is equal null if you understand what i mean

south forge
#

like using a for loop? or going through the array in a loop like going back to the first index once ive reached the end?

crimson rune
#

Hey, my tiles are not being rendered. ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridManager : MonoBehaviour
{
[SerializeField] private int _width, _height;
[SerializeField] private Tile _tilePrefab;
[SerializeField] private Transform _cam;

void Start()
{
    GenerateGrid();
}

void GenerateGrid()
{
    for(int x = 0; x < _width; x++) {
        for(int y = 0; y < _height; y++) {
            var spawnedTile = Instantiate(_tilePrefab, new Vector3(x, y), Quaternion.identity);
            spawnedTile.name = $"Tile {x} {y}";

            var isOffset = (x % 2 == 0 && y % 2 != 0) || (x % 2 != 0 && y % 2 == 0);
            spawnedTile.Init(isOffset);
        }
    }

    _cam.transform.position = new Vector3((float)_width/2 -0.5f, (float)_height/2 -0.5f, -10f);
}       

}

jade heart
#

Hi everyone, so I have a problem regarding Shader Graph, basically the material is not being rendered as you can see in this image.

How may I fix the issue?

#

It's weird to me since previously I haven't got this issue.

#

Also, if I'm talking in the wrong channel let me know and I will use the correct channel for the next time.

regal marsh
#

so i have a spawner and i want it to only spawn up to x items. my plan was to keep track of the items it has spawned in a list and then once it hits max, check every frame to see if any of the items have been destroyed. is there a better way?

jade heart
regal marsh
#

it sounds very unoptimized lol

#

wait i have another idea hang on

soft shard
# regal marsh so i have a spawner and i want it to only spawn up to x items. my plan was to ke...

Not knowing the full context of your use-case, I would suggest maybe using events instead of Update/checking every frame, either send a System.Action or delegate to some manager before you destroy the object, or "broadcast" the destroy event with for example a "Publisher-Subscriber" pattern, then the object doesnt need to send anything to a manager, but the manager can listen for when something gets destroyed and update your list accordingly

crystal kite
#

anyone know how to render just part of a render texture onto a raw image?

pastel wren
#

can someone help me with this new character i imported from asset store, how do i make the character perform a certain one of these animations

velvet quartz
#
_animator.SetLayerWeight(1, Mathf.Lerp(_animator.GetLayerWeight(1), 0f, Time.deltaTime * 13f));

--> Time.deltaTime * 13f // This value indicates how fast the transition does ?
proper oyster
celest condor
#

Hi I need some help. The game works fine, but when I build it, the camera stays in the starting position and is not moving with the player. How do I fix it?

swift falcon
#

have u coded that in @celest condor

celest condor
#

I just built the game again and the problem is fixed

#

Unity moment lol

#

Thanks anyway tho

quartz folio
#

vertices are in local space

gilded grove
#

I've read that, but didn't understand how to update the transform. Knowing that's the right direction, I'll look into it again. Thank you

karmic stratus
#

anyone know what this error means: ArgumentException: Could not cast or convert from System.String to RandWord.

#

im trying to call an API but whenever i deserialize the json it gives me that error

#

here is my deserialization code:

 HttpWebRequest randrequest = (HttpWebRequest)WebRequest.Create("https://random-word-api.herokuapp.com/word");
        HttpWebResponse randresponse = (HttpWebResponse)randrequest.GetResponse();
        StreamReader randreader = new StreamReader(randresponse.GetResponseStream());
        string randjson = randreader.ReadToEnd();
        List<RandWord> randresult = JsonConvert.DeserializeObject<List<RandWord>>(randjson);```
celest condor
#

Could anyone help me find a bug in a movement code?

#

The code is bit longer though

#

Nevermind. I figured it out

swift falcon
#

yo trying to make my first game! i want to make a horror game but where can i get a good fps controller from that you import and it instantly works without changing anything

celest condor
#

The default Unity one is pretty good

#

It even has sounds

swift falcon
#

where can i get that from?

#

or is it the preinstalled one?

buoyant crane
stuck forum
#

Anyone who is familiar with DateTime, is it possible to write this but with hopefully one line only? Or do I really need to break it up into parts like I am currently doing?

dateText.text =
    DateTime.Now.ToString("MMM", CultureInfo.InvariantCulture).ToUpper()
    + "." 
    + DateTime.Now.ToString(" dd", CultureInfo.InvariantCulture)
    + DateTime.Now.ToString(" yyyy", CultureInfo.InvariantCulture);
#

Also for time, if I use the en-US culture thing, it says for example 2:23 AM, but I'd like the AM part to be in front instead

quaint rock
#

can you not do a DateTime.Now.ToString("MMM. dd yyyy").ToUpper() ?

stuck forum
#

Oh that worked, honestly I never used the format parameter thing for ToString so didn't know you could combine them

#

thanks!

quaint rock
#

well these are a special case of ToString for formatting dates

robust osprey
#

Hi all, I am having trouble painting to textures in code, I posted over in #🖼️┃2d-tools but really not sure where to look for expertise on this. Basically trying to use .SetPixel (r,g,b,a) on a 2D texture in a 3D game ... but finding that a (alpha channel) does nothing, here's the post:
#🖼️┃2d-tools message

swift falcon
#

How do i make the lightning dark?

warm wren
swift falcon
#

nvm got a effect i like

viscid plover
#

I'm having difficulty trying to create a dashing ability that is aimed via a thumbstick. What I'm attempting right now is using the global position of the reticle minus the position of the player, normalized, and then adding force. But I'm getting some really funky behavior (shooting me straight down or straight up no matter what position the reticle is in). I've also tried:

`Vector2 direction = new Vector2(reticlePos.x, reticlePos.y).normalized;

player_rigidbody2d.velocity = new Vector2((direction.x * 10), (direction.y * 10));`

#

Is there a simpler way to shove my character in the direction of my reticle?

#

or... any way to do so, simple or not. 😛

#

The reticle is a child object of my player prefab, and has its transform altered as I move the thumbstick. It's a constant distance from my character, in a circle. If that matters.

vital thorn
#

Does anyone know how to deform a mesh based on a binary mask? Wherever the mask is white I would like to contract/shrink the mesh

velvet quartz
#

When and why use a public variable instead of private? Shouldn't we always use private and have a Set / Get function if necessary? So what is a public variable for?

zinc parrot
#

so if I have this
and I do Object[] A = Resources.LoadAll(smallCampfireVDB);
why is the length of A 0? even tho that folder is filled with text files

somber nacelle
tawny rose
#

how to detect the if the letter is on the slot in onenddrag

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

public class DragDrop : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler {


    public static bool InSlot = false;
    [SerializeField] private Canvas canvas;

    private RectTransform rectTransform;
    private CanvasGroup canvasGroup;
    public GameObject self;
    public bool canSetPosition = true;

    public void Check()
    {
    }
        

    private void Awake() { 
        rectTransform = GetComponent<RectTransform>();
        canvasGroup = GetComponent<CanvasGroup>();
    }

    public void OnBeginDrag(PointerEventData eventData) {
        Debug.Log("OnBeginDrag");
        canvasGroup.alpha = .6f;
        canvasGroup.blocksRaycasts = false;
        InSlot = false;

    }
    void SetPositoin()
    {
        self.GetComponent<Letters>().setPositon();
        
    }
    public void OnDrag(PointerEventData eventData) {
        //Debug.Log("OnDrag");
        rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor;
        
        //SetPositoin();
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("OnEndDrag");
        canvasGroup.alpha = 1f;
        canvasGroup.blocksRaycasts = true;
        List<GameObject> slots = GameManager.Slots;
        Debug.Log("--------->" + slots);
        bool isOnSlot = false;
        foreach (GameObject slot in slots)
        {

            if (self.transform.position == slot.transform.position)
            {
                isOnSlot = true;
                Debug.Log("-------------------------------> Same Posiiton");

            }
        }
        if (!isOnSlot)
        {
            SetPositoin();
        }
    }

    public void OnPointerDown(PointerEventData eventData) {
        Debug.Log("OnPointerDown");
    }

}```
#

some pls help

prime sinew
tawny rose
#

ggamemanager.slots

prime sinew
#

never mind, i'm confused

tawny rose
prime sinew
#

you can't just dump a whole script without context on what your structure is

#

what do you mean letter, what slot?

#

what are you trying to do? what isn't working?

tawny rose
#

u want the github link

prime sinew
#

no. i want your explanation

#

again, no context for what you mean by github link

#

link to your own repo? the github to the tutorial you got this from?

tawny rose
#

my repo

prime sinew
#

so what do you want to do, and what isn't working?

tawny rose
# prime sinew no. i want your explanation

soo im trying to implement replace(where u take a block and place it on top of a slot thiat is occupied and the tile in the slot goes to its original position and the new tile snaps into place)

#

does it make sense??

prime sinew
#

okay, so what's the trouble here

tawny rose
#

soo the trouble is it dosent call ondrop when the slot is occupied so i need to detect in onendrag

prime sinew
tawny rose
#

it is in a script named item slot :

using System.Collections.Generic;
using Unity.VisualScripting.Antlr3.Runtime.Misc;
using UnityEditor.UI;
using UnityEngine;
using UnityEngine.EventSystems;

public class ItemSlot : MonoBehaviour, IDropHandler
{
    public GameObject self;
    public GameObject Slot1;
    public GameObject Slot2;
    public GameObject Slot3;
    public GameObject Slot4;
    public bool isFilled = false;
    public GameObject baseLetter;
    public GameObject b;
    public void OnDrop(PointerEventData eventData)
    {
        Debug.Log("OnDrop");
        if (eventData.pointerDrag != null)
        {
            if (isFilled && baseLetter != null)
            {
                baseLetter.GetComponent<Letters>().setPositon();
                isFilled = false;
                Debug.Log("Chaning");
            }
            eventData.pointerDrag.GetComponent<Letters>().FillObjectList();
            baseLetter = eventData.pointerDrag;
            eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = self.GetComponent<RectTransform>().anchoredPosition;
            Debug.Log(self.GetComponent<RectTransform>().anchoredPosition);
            isFilled = true;
            DragDrop.InSlot = true;
            Letters.a = false;
        }
    }


} ```
#

@prime sinew ^

prime sinew
#

I see

#

easiest way is to just move the detecting image on top of the itemslot, above the block that's occupying the slot

#

and it checks if the slot is occupied or not. if it's occupied, then get the block that's in the slot and yeet it out

#

if not, then place the block you're dragging into the slot

tawny rose
#

sorry had a meeting

#

no but im not able to detect the block on top that @prime sinew

prime sinew
tawny rose
#

no it is on the slot itself

prime sinew
#

yes, and i'm telling you.... make it not on the slot

#

the slot is blocked by blocks

#

so you cant have the dropping part be detected by the slot itself

#

separate the slot logic from the drop detection part

swift falcon
#

I am trying to update the Z position when I click on a game object so what I did is
transform.position = new Vector3(transform.position.x, transform.position.y, 1.3f);

#

but for some reason nothing happens

prime sinew
#

we'll need to see where you called that code

#

that code alone seems fine

#

!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.

prime sinew
#

but I can see you're using OnMouseDown

#

that's all I really needed to know

#

OnMouseDown requires a collider on the object

cunning shard
#

Is there any way to change lang version to C# 9 on unity < 2021?

swift falcon
somber nacelle
swift falcon
somber nacelle
#

look at line 37

cunning shard
somber nacelle
#

lol "internal issues" prevent you from updating the editor, but not bastardizing the editor to do what a more recent version would do anyway?

cunning shard
#

Unity must be 2020.3.36f1

#

Still, I need C# 9 syntax sugar

somber nacelle
#

well it's a good thing that's all you would get. but anything you can do with syntax sugar in c# 9 should be doable in other ways in previous versions

#

but have fun figuring that out, i'm not going to give directions just for you to go and break your project 🤷‍♂️

plucky karma
#

Seeing this as a general for coding - Has anyone seen that ProgrammerHumor posting about Dutch's open source government tool on loading bars?

cunning shard
somber nacelle
plucky karma
thick gale
#

at what point should a script be broken up into multiple? How often does too much stuff being in one code cause issues?

somber nacelle
#

when a class does too much, it becomes harder to debug as well as to maintain

thick gale
#

simple enough, appreciate the insight

sour trench
#

Should I use uint instead of int when I don't want negative values to be possible? Are there any memory concerns I should be aware of? I've been reading different threads on this this morning but I can't seem to come to a conclusion since everyone seem to have their own opinion 😅

prime sinew
maiden fractal
# sour trench Should I use uint instead of int when I don't want negative values to be possibl...

You could but you dont have to, I myself and many others dont bother writing that extra "u" when it doesnt matter, when you want to go to values higher than 2.1 billions, usually 4.3 isnt enough either, so in that case long or ulong would be the way to go. The decision between int and uint has nothing to do with memory or performance, that sign bit is used to support about 2x larger values (both use 32 bits of memory) and modern CPUs can perform calculations with both really fast

potent glade
#

question, in this next code the debugger is showing me SUCCESS, but the deserializedProduct doesn't have the ID value.. what is the reason??
(the class Deserialized has the same fields as the received information and in the same spelling and same upper/lower case.... I made sure of that multiple tmies)

            UnityWebRequestAsyncOperation operation = www.SendWebRequest();
            while (!operation.isDone) { await Task.Yield(); }
            if (www.result == UnityWebRequest.Result.Success)
            {
                string jsonData = www.downloadHandler.text;
                Debug.Log("success");
                Debug.Log("Form upload complete!" + jsonData);
                Deserialized deserializedProduct = JsonConvert.DeserializeObject<Deserialized>(jsonData);
                Debug.Log("recieved result: " + deserializedProduct.id);
            }
maiden fractal
sour trench
#

@maiden fractal I'll probably stick with int then, just annoying to know that values can be less than zero and you have to handle it everywhere..

prime sinew
sour trench
#

@prime sinew Like [Min(0)] you mean?

prime sinew
sour trench
#

@prime sinew Ah, yeah not a bad idea I guess.

potent glade
crimson atlas
#

whats the best way to store scriptable objects of type to be loaded at runtime?
canne use Resources.Load as that goes kaput when building.
canne use AssetDatabase as that goes kaput when building.

is the only way to slap an array of the type on a monobehaviour component in the scene, add all the objects to that and call it a day?

somber nacelle
#

Resources.Load absolutely does work in a build. obviously AssetDatabase won't. but your other options are addressables, or direct references

crimson atlas
#

oh damn ive only ever had nightmares trying to load stuff from resources in a build haha!
been using streamingAssets to store things like tilemaps and json files n stuff

somber nacelle
#

as long as you follow the law of the Resources folder it should work just fine

crimson atlas
somber nacelle
#

the objects loaded using the Resources class must be within a folder named Resources

wild vigil
#

I'm placing objects in the scene by script using a raycast. Can't figure out how to rotate each object on its local up. Any ideas?

somber nacelle
#

there's also just Transform.Rotate with the Space parameter

crimson atlas
#

so something like this should work? and its gonna ignore all the .meta files?

somber nacelle
#

it will not load meta files, correct

crimson atlas
#

woo danke danke

somber nacelle
#

also don't include the extension in the path

crimson atlas
#

on it boss!

wild vigil
somber nacelle
#

then you worded your question incredibly poorly because you implied that you were trying to rotate the objects you are spawning. and if that is not the case, please provide more information

wild vigil
somber nacelle
#

well the actual question you did ask was easily googleable, notice how i provided 3 pieces of information all super quick like that?

crimson atlas
#

;-; insert gif of cat from puss in boots going oooooo
but dont because i think it against rules
possibly a popcorn gif too?

#

rooting for u boxfriend u save my nea!!

wild vigil
#

I worked it out. Just needed to convert my raycast normal into a quaternion and multiply by another quaternion for the rotation.

sour trench
#

Why is data null here despite being set in the editor? Is this some weird timing issue I'm not aware of?

    public NPCData data;

    // constructor
    NPCController()
    {
        Debug.Log(data);
        attributes = new NPCAttributes(data);
quartz folio
#

You should use Awake or Start generally

#

Any work done to serializable fields will be overridden after the constructor runs. And Unity doesn't like many things happening in that time too

ancient cloak
#

you shouldn't be using the constructor in scripts essentially

#

think of Awake as the constructor, Start as like a "late" constructor if you depend on other initialized scripts

sour trench
#

@quartz folio @ancient cloak I see. So no constructor use when using MonoBehaviour basically.

quartz folio
#

Generally not advised

sour trench
#

@quartz folio Not ideal in other scenarios I found, such as this one:

public PlayerController() {
        skills = new BaseSkills();
        attributes = new PlayerAttributes(skills);
        equipment = new PlayerEquipment();
        inventory = new PlayerInventory(this);
}

If I have it in Awake then any changes made in the editor is gone when I launch the game, I know this would be solved with data persistence (which I haven't added to the player yet) but when that isn't enabled it would be very annoying to work with temporary player state cuz I would have to always set it after I launch the game.. 🤔

quartz folio
#

If you're wanting to initialise things via code don't serialize them

#

Make them private, or mark them as [NonSerialized]

#

If you're wanting what is serialised in the editor, don't set them via code

ancient cloak
#

also if you're instantiating scripts via script you shouldn't construct them, you should use GameObject.Instantiate

wild vigil
#

Can I lock a gameobject transform from being moved or rotated?

#
    {
        transform.hideFlags = HideFlags.NotEditable | HideFlags.HideInInspector;
    }```
#

I've got this little gen that hides it in the inspector

ancient cloak
#

move that to awake, not onvalidate

#

not your question though sorry continue

sour trench
#

@ancient cloak None of the scripts in the constructor are MonoBehaviour scripts though. @quartz folio I basically want to initialise via code but change values via the editor (or code at runtime for adding items to inventory/equipment for example). Thoroughly confused how to achieve that based on what you said 😅 Maybe the best way is to remove the "dependencies" from PlayerInventory and PlayerAttribute, that way I don't have to initialise via code..

ancient cloak
#

oh i wasn't sure since you were constructing the script

quartz folio
wild vigil
ancient cloak
#

it looks the same but OnValidate is triggered whenever you edit a value in the inspector. it doesn't make sense to set your hide flags every time the editor is modified

#

you could also do it in update

#

you could do it 500 times every update

#

makes just as much sense as doing it in onvalidate LUL

sour trench
#

@quartz folio Because I need a reference to PlayerController in PlayerInventory for example:

    public PlayerInventory(PlayerController controller)
    {
        this.controller = controller;
        storage.MaybeCreateSlots();
    }

    public void UseItem(BaseSlot<ItemData> data)
    {
        data.itemData.Use(controller);
    }

Otherwise how does PlayerInventory get the reference if not via its constructor? Only way I see is what I said and make PlayerController controller a parameter of UseItem instead.

ancient cloak
#
private void Awake()
{
  _playerInventory = new PlayerInventory(this);
}
quartz folio
#

If it's not also serialized and set in the inspector, then you can just make a method that you call with those non-serialised parameters

ancient cloak
#

there's also a design consideration of - why does your inventory need to know how the player uses an item?

quartz folio
#

Just allow the editor to create serializable things, and then set anything extra in Awake via methods or properties. You could also choose to separate the serializable representation from the one you construct entirely

ancient cloak
#

do you have a little gremlin in your backpack

#

logic would dictate that you treat the inventory as either a simple construct - a container of values, or a class with Add/Remove/Sort functionality etc

lament sentinel
#

Is there a way to create a generic type method to return either a Float, Vector2 or Vector3 ?

Example

public Object ProgressValue<Value> ( ) where Value:  UnityEngine.Object{
            Value value = null;
            switch ( tweenType ) {
                case TweenType.VECTOR3:
                    value = progressOfVec3;
                    break;
                case TweenType.VECTOR2:
                    value = progressOfVec2;
                    break;
                case TweenType.FLOAT:
                    value = progressOfFloat;
                    break;
            }
            return value;
        }
ancient cloak
#

IMO your inventory should only be responsible for things that an inventory does. not what things do with the items in an inventory

quartz folio
#

So that constraint makes no sense

sour trench
lament sentinel
quartz folio
#

The convention says generic types should start with T

#

So you would return T and cast what you return

ancient cloak
#

@sour trench but why does the inventory need to tell the player how to use an item

wild vigil
ancient cloak
#

why can't the player just take an item from the inventory

sour trench
#

@ancient cloak You mean when I click an item in my inventory, why the UI script doesn't just call Use directly?

mental rover
ancient cloak
#

your inventory is caching a reference to the player that owns it, specifically so it can tell the player how to use an object

#

does'nt make sense. that's something the PlayerController is doing in reality

#

and beyond that, the item is taking a reference to the player controller so IT can tell the player how to use IT

dense hamlet
#

An idea how to be able to add muscle growth to my character?

ancient cloak
#

thats super vague

#
_muscleValue++;
sour trench
#

@dense hamlet Protein powder and lots of hard work.

wild vigil
sour trench
wild vigil
#

could also blend in a normal map that shows muscle definition.

ancient cloak
#

the player should just remove the item from the inventory and use it directly

#

you can do what you want, it's just unnecessary coupling. now you have to refactor or duplicate your code if you want anything besides a player to have an inventory

#

like a chest or an npc

wild vigil
#

Is there a monobehaviour function that recognizes focus in the hierachy?

ancient cloak
#

what are you trying to accomplish

wild vigil
#

I'll try asking in editor-extensions

ancient cloak
#

why

#

just answer my clarifying question and i can answer you better

wild vigil
#

its more of an editor I guess

ancient cloak
#

are you trying to make an object that nobody can modify in editor or something that wont' be affected by physics or game logic

wild vigil
#

correct

ancient cloak
#

that was an or question

wild vigil
#

cant be modified

ancient cloak
#

make it static

wild vigil
#

make it static?

ancient cloak
#

you can also make it unselectable

wild vigil
#

yeah, I'll try that one

ancient cloak
#

either by locking the object individually in the hierarchy or locking an entire layer

#

click the hand icon next to the gameobject and it'll toggle to unselectable

west lotus
#

There is also this

ancient cloak
#

it makes debugging easier when you have a thoroughly tested prefab. it's not necessary to view its full hierarchy

#

so i make a habit of modifying "finalized" prefabs so their children get hidden

west lotus
#

Maybe this is more of what the guy wants

wild vigil
ancient cloak
#

you shouldn't be able to select it

#

sec i need to open unity now

wild vigil
#

nah, you are right

#

it doesnt move

#

Is there a way to flag that in code?

ancient cloak
#

you really don't want to edit it at all no matter what? sheesh

#
[ExecuteInEditMode]
public class UneditableObject : MonoBehaviour
{
    private void Awake()
    {
        gameObject.hideFlags = HideFlags.NotEditable;
    }
}
#

there you go, if that's what you really want

wild vigil
#

beutiful

#

beautiful

ancient cloak
#

keep in mind once you add that script it's uneditable

#

including being able to remove scripts from it

#

so have fun with that LUL

#

you'll have to edit this script in order to gain control back

wild vigil
#

There is just a single script on it

ancient cloak
#

as you can see once you add it you can't take it off

wild vigil
#

😆 - perfect

ancient cloak
#

a way around that might be to create a scriptable object that acts like a "scene lock" so you can modify the hide flags of any value that has the script but the scriptable object itself isn't locked so you can turn the hide flags back off

wild vigil
#

I'll look into that

#

I want to use a scriptable object now to store my list

ancient cloak
#

it would be something like

#
[CreateAssetMenu(menuName = "SceneLock")]
public class SceneLock : ScriptableObject
{
  [field: SerializeField] public HideFlags HideFlags {get;}
}
[ExecuteInEditMode]
public class SceneLockObject : Monobehaviour
{
  [SerializeField] private SceneLock _sceneLock;  
  private void Awake()
  {
    gameObject.HideFlags = _sceneLock.HideFlags;
  }
}
#

might need onvalidate for this implementation

wild vigil
#

I should pay you to help me out. Things would go a lot faster.

#

This struggle is good for me. No pain no gain.

ancient cloak
#

it's not a terrible idea. sounds like you have a moron designer. and i'm all for disabling moronic designers

wild vigil
#

Yeah, I am the designer 😆

ancient cloak
#

oh LUL

wild vigil
#

You are not far off.

ancient cloak
#

i developed something that honestly i should add to the asset store

#

a [Required] attribute that enforces a serialized value to have an assigned value in the inspector

#

because in grad school i had a freaking moronic designer who refused to learn that you need to pull down before pushing code

#

so he BLASTED my UI changes 6 times in a row the day before we were presenting

wild vigil
#

ha - guy was doing what designers do best

ancient cloak
#

fr

wild vigil
#

artists and designers should be kept away near any deadlines

ancient cloak
#

low key, so i have a coworker, and i hate throwing shade cause he's an awesome guy

#

but we have this system at work that we read in csv files and generate assets, serialize them and send them to a database. the tool exists in the game project itself to convert the csv files and upload them to the DB

#

and he has been updating the CSV's for months and just not committing them to version control

#

so the conversion tool is useless for everyone but him

wild vigil
#

he holds the infinity stones. Smart guy.

cold parrot
ancient cloak
#

and we had a problem recently where the db got corrupted and i was like "oh no big deal i can just run the conversion tool real quick" that was rough

cold parrot
ancient cloak
#

when asked why he didn't commit them, he said he still hasn't figured out sourcetree. we just shipped a few months ago

sour trench
#

So in my BaseController I have a public BaseAttributes attributes field, but my derived classes NPCController and PlayerController need to have two different types; NPCAttributes and PlayerAttributes respectively. How do you actually make them create the correct class without manually initialising them? I guess what I'm looking for is some sort of virtual/override pattern but for fields (or properties).

ancient cloak
#

@cold parrot it's a scene with a suite of editor scripts

cold parrot
ancient cloak
#

enough. it's like a foundational framework for whats going to be a standalone tool

#

our tool dev is pushing to make it a web tool. but like it's so frustrating because if it's an internal tool why not just make it a standalone unity exe. why bother making an asp.net web app or a standalone wpf app

#

the data has to go back into unity anyway

#

im ranting LUL

#

hosting costs are a real thing. why pay for a server for something that 3 people are going to use

#

i've noticed there are people with like google brains and people with startup brains

wild vigil
#

I've heard far worse tales than this one bard.

ancient cloak
#

you know NASA spent millions of dollars designing a pen that can write in space? russians brought pencils

soft shard
# sour trench So in my `BaseController` I have a `public BaseAttributes attributes` field, but...

You could use the constructor of those classes if the BaseController is not a MonoBehaviour - if it is, you could maybe try making it a BaseController<T> and making a new instance of your attributes, otherwise you could make a virtual Init function and pass what you need to it, but since they may be different types, it may be harder to generalize it that way, depending on what makes your attributes different, aside from file names

cerulean sierra
#

yo can someone help me out unity says sum thing is wrong with my grappler code it says warning CS0108 'GrapplingGun.camera'hides inherited member'Component'. Use the new keyword can some one help me fix it

cold parrot
ancient cloak
#

i had to launch and maintain 3 api's and a mongo server last cycle because we didn't have a web guy, and i'm like you want MORE web tools?

cold parrot
ancient cloak
#

especially since there's like 12k google brains without jobs now

cold parrot
#

the whole web world rn, in their practices are pretending they are Google/Netflix

soft shard
ancient cloak
#

or put it in a different namespace

cerulean sierra
#

ok thanks

ancient cloak
#

making namespaces match your folder structure is super handy

wild vigil
#

I'm an artist thinking about starting a comp sci degree.

#

Would likely take me a decade.

cerulean sierra
soft shard
#

I tend to try and put all my "system" code or base class type code in namespaces then have things that inherit from it or use it in some way have using My.Namespace, just to keep things organized and remind my dumb brain when I might be "overstepping" functionality

ancient cloak
#

comp sci i sn't that hard. most difficulty in learning is lack of faith in yourself

soft shard
#

Like if I wanna reference the audio system, and VS suggests "do you want your character controller to use the audio namespace?" it reminds me "do I really NEED it to? I must have done it this way for a reason"

mental rover
wild vigil
ancient cloak
#

@cerulean sierra so you have a root namespace that matches your project name, say "Foo". then you have your Assets/Scripts folder as your root folder for all your scripts. then say you have a UI folder in Scripts. then any script in that folder would be like:

namespace Foo.UI;
public class MyUiScript
{
}
#

the unscoped namespace is a c#10 feature actually my bad

cerulean sierra
#

mk

soft shard
#

^ Youd have to encapsulate the class in the namespace though

ancient cloak
#

pre c#10 yes

#

so

namespace Foo.UI
{
  public class MyUiScript
  {
  }
}
soft shard
#

Oh, didnt know you can do that in 10, C# 9 and 10 seem to have a lot of very nice features

ancient cloak
#

yeah i think it wasn't even until like c#8 where you could bake in nested namespace scopes

#

back in c#4 i remember writing

namespace Foo
{
  namespace UI
  {
    public class MyUiScript
    {
    }
  }
}
#

so people would have gross conventions where they wouldn't indent any nested namespace scope and it looked terrible

soft shard
#

Ohwow, I actually thought the dots was just the "path" you want to give it (like the "path" of a CreateAssetMenu), I guess it makes sense its technically nesting namespaces, that is very gross though for namespaces lol

ancient cloak
#

yeah it technically is a path, tha'ts why c# changed it because it became such convention to have very narrow namespace resolution to minimize aliasing

#

makes it super helpful if you're using a lot of 3rd party assemblies. type aliasing is a huge bitch

#

cause then you gotta reach out to the 3rd party companies, make a feature request or ask for an exposed source code option and then you're boned if you ever need an update cause you gotta propagate your changes

soft shard
#

Daam, we come a long way-since

cerulean sierra
#

🥲

ancient cloak
#

Sure

cerulean sierra
#

mk

wide fiber
#
public class S_BossSpawnManager : MonoBehaviour
{
    [SerializeField] LevelSO[] Stage;
    [SerializeField] int stageSelect;

    private void Start()
    {
        stageSelect = 0;
    }

    private void Update()
    {
        SwitchingLevel();
    }
    void SwitchingLevel()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            stageSelect = Random.Range(0,Stage.Length);
        }
    }

    void onThisLevel()
    {
        switch (stageSelect)
        {
            case 0:
                Stage = 0;
                break;
        }
    }
}
--------------------------Scriptable object script--------------------------------------
[CreateAssetMenu(fileName = "Stage0", menuName = "Stages", order = 2)]
public class LevelSO : ScriptableObject
{
    public GameObject stages;
}

hi sorry, under "switch" there's seems to be an error. How do i select a certain stage under LevelSO?

#

its a scriptable object

prime sinew
vocal merlin
#

Stage is an array, you're trying to assign an int to it

wide fiber
prime sinew
#

Someone already told you what's wrong

prime sinew
#

Stage is an array. It holds a collection of ints

#

It is a container holding ints. You cannot say it is an int

#

It is a container

#

So what you're doing doesn't make sense. What are you trying to do?

wide fiber
vocal merlin
#

Stage is an array holding LevelSO scriptable objects

wide fiber
#

wah ok i think i over-engineer things

vocal merlin
#

I would assume you need something like a public variable that is LevelSO currentLevel and set that from the array

#

Or return the LevelSO from the omThisLevel function instead of void, no need for the switch statement, you could just say return Stage[selectedStage]

#

Obviously checking that selectedStage is inside the array before hand

wide fiber
#

i will try this

mental rover
#

as it is the code doesn't make much sense at all and you might be better helped in concept rather than specific syntax here

wide fiber
wary prism
#

Any recomendations for a something to use for a simple 3 online game (lightweight for just me and friends)
I tried photon but it seemed outdated, or maybe I was using the wrong version or something idk

A youtube tutorial would be perfect too

#

(@ me)

pulsar root
#

Hi there! I have a weird problem in Unity Build (which not happens in fast build) which I cannot find a solution. If my document is initialy disabled in scene (doc.enabled = false) and then I try to query an element in Awake, OnEnable, ... for example var winMenuSection = doc.rootVisualElement.Q<VisualElement>("WinMenuSection"); it is null for some reason

pulsar root
#

I see that if I don't disable it's working in both fast build and build and run

#

public void changeWinMenuVisible(bool isVisible)
{
if (isVisible)
{
doc.rootVisualElement.visible = true;
UnityEngine.Cursor.visible = true;
UnityEngine.Cursor.lockState = CursorLockMode.None;
}
else
{
doc.rootVisualElement.visible = false;
UnityEngine.Cursor.visible = false;
UnityEngine.Cursor.lockState = CursorLockMode.Locked;
}
}

#

this works but I don't like it since document disabled is more efficient to handle than a hidden view

rain minnow
pulsar root
#

Hello, I have the hierarchy in the top i'm calling it in WinMenuUIController

karmic stratus
#

anyone know what this error means: ArgumentException: Could not cast or convert from System.String to RandWord.
im trying to call an API but whenever i deserialize the json it gives me that error
here is my deserialization code:

HttpWebRequest randrequest = (HttpWebRequest)WebRequest.Create("https://random-word-api.herokuapp.com/word");
       HttpWebResponse randresponse = (HttpWebResponse)randrequest.GetResponse();
       StreamReader randreader = new StreamReader(randresponse.GetResponseStream());
       string randjson = randreader.ReadToEnd();
       List<RandWord> randresult = JsonConvert.DeserializeObject<List<RandWord>>(randjson);```
pulsar root
#

The only workaround works for me is to have it enabled by default

#
    {
        if (isVisible) 
        {
            doc.rootVisualElement.visible = true;
            UnityEngine.Cursor.visible = true;
            UnityEngine.Cursor.lockState = CursorLockMode.None;
        } 
        else
        {
            doc.rootVisualElement.visible = false;
            UnityEngine.Cursor.visible = false;
            UnityEngine.Cursor.lockState = CursorLockMode.Locked;
        }
    }```
#

And then do that...

pulsar root
#

So you have to do that

#

List<String> randresult = JsonConvert.DeserializeObject<List<String>>(randjson);

#

Since it's a **value and not a key value **

karmic stratus
#
randword = randreader[0].
pulsar root
#

What is RandWord

#

a class? which structure has it?

karmic stratus
pulsar root
#

Don't get at all what you are trying to do here. First of all you get a list of words from the api which is a single word as far as I can see for example ["literateness"]

#

so doing that -> List<String> randresult = JsonConvert.DeserializeObject<List<String>>(randjson);
you are converting "["literateness"]" to -> List of strings which contains that word at the first position of that list

#

So to access the word itself you have to do String word = randresult[0] and you will get that word "literateness"

#

Class RandWord is not needed here since the structure of the result of the api is not that one

karmic stratus
#

hopefully that makes sense

pulsar root
#

Yes but this -> List<RandWord> randresult = JsonConvert.DeserializeObject<List<RandWord>>(randjson);

#

is this -> ```[{RandomWords: ["hi"]}, {RandomWords: ["hi"]}]````

karmic stratus
#

thanks :)

dense cypress
#

hi gang

#

i have a chunk based procedural system that calculates all of the noise, generating around 8+ chunks per second around the player. i tried to implement pooling in a queue but when they are pulled off the queue all the chunks become a single and repeated chunk. any ideas?

#

doesnt seem able to add the data the same way as when i create a new object

mental rover
dense cypress
#
c = new Chunk(chunkPosition, textureAtlas, prefab, chunkfab);
              c.chunk.name = n;
              c.chunk.transform.position = chunkPosition;
              c.chunk.transform.parent = this.transform;
              chunks.TryAdd(c.chunk.name, c);```
#

instead of:

#
              if (chunkPool.Count > 0)
              {
                Debug.Log("Loading chunk from pool");
                c = chunkPool.Dequeue();
              }
              else
              { 
                Debug.Log("Creating new chunk");
                 c = new Chunk(chunkPosition, textureAtlas, prefab, chunkfab);
              }

              c.chunk.name = n;
              c.chunk.transform.position = chunkPosition;
              c.chunk.transform.parent = this.transform;
              chunks.TryAdd(c.chunk.name, c);```
ancient cloak
#

oh god

#

use a paste link please

dense cypress
#

oh u mean a code thing for visaging da codus

#

code block no good?

#

ill read that

ancient cloak
#

small code blocks are fine with syntax highlighting

#

cs after the first 3 ticks

dense cypress
#

done

ancient cloak
#

can you show your whole code

#

i can't tell if you're running a coroutine or not or where you're triggering it

dense cypress
#
    void BuildChunkAt(int x, int z)
    {
        int posx = (int)Mathf.Floor(player.transform.position.x / chunkSize);
        int posz = (int)Mathf.Floor(player.transform.position.z / chunkSize);

         Vector3 chunkPosition = new Vector3((x + posx) * chunkSize, 0, (z + posz) * chunkSize);

          string n = BuildChunkName(chunkPosition);
          Chunk c;

          if (!chunks.TryGetValue(n, out c))
          {
              // check if there are any chunks in the pool to reuse
              //if (chunkPool.Count > 0)
              //{
                //Debug.Log("Loading chunk from pool");
                //c = chunkPool.Dequeue();
              //}
              //else
              //{ 
                //Debug.Log("Creating new chunk");
                 //c = new Chunk(chunkPosition, textureAtlas, prefab, chunkfab);
              //}
              c = new Chunk(chunkPosition, textureAtlas, prefab, chunkfab);
              c.chunk.name = n;
              c.chunk.transform.position = chunkPosition;
              c.chunk.transform.parent = this.transform;
              chunks.TryAdd(c.chunk.name, c);
          }
    }```
#

the commented out code is where i tried to swap in the queue system

mental rover
#

when you dequeue, it's not going to call the constructor again as the object already exists

dense cypress
#

gotcha

#

how do i do that my lovely friend

ancient cloak
#

you can use an actual object pool

mental rover
#

simplest way would be to move all initialisation into an Initialisation method, call that from the constructor, and also call it after being dequeued

ancient cloak
#

object pools have callbacks for construction and retrieval

dense cypress
#

is that the proper one with the whole <T> business

mental rover
#

or what Stropheum is suggesting, it would be nice if that sort of thing is handled in the pool system itself

dense cypress
#

just to clarify, there is no way to call the constructor again as the object already exists?

#

nothing straightforward i mean

ancient cloak
#

you can override it with a new allocation

#

defeats the purpose of preallocating them

dense cypress
#

caveat

#

roj

#

that makes sense though guys thank u so far

dusk apex
dense cypress
#

so a true object pool system would solve this?

ancient cloak
#

yes, because you can use ontakefrompool to configure the already allocated chunk

mental rover
#

depends on what you mean by solve - it would be a wrapper that does these standard methods in a generic fashion for every object so you can reuse the pooling structure in other code

gentle hinge
#

How can I reduce wobbling on a configurable joint being used as a spring?

mental rover
#

you don't need that complexity in a one-off case

gentle hinge
#

I want the main object to move smoothly towards the other instead of flying around the joint

ancient cloak
#

show

dense cypress
#

i was doing this to create objects in my queue

   // void CreateChunksInPool(int amount)
   // {
   //     for (int i = 0; i < amount; i++)
   //     {
   //        Vector3 fakePosition = new Vector3(0, 0, 0);
   //         Chunk c = new Chunk(fakePosition, textureAtlas, prefab, chunkfab);
   //         chunkPool.Enqueue(c);
   //     }
   // }```
#

just double checking that i didnt do anything wrong there

ancient cloak
#

the solution for your existing code is to wrap your queue in code that detects a queue pop and does some initial setup. but why not just use a data structure that already optimally preallocates memory and supports callbacks for every phase of interaction

dusk apex
#

Google a tutorial and return after getting some working system that's got issues or concerns.

dense cypress
#

i take it its just a limitation for the reasons you guys said

#

its bypassing the constructor right

ancient cloak
#

there's no bypassing

#

any object is constucted one time and one time only

mental rover
karmic stratus
#

how do I loop back if I catch an error? my random word api has a larger dictionary of words than my dictionary api so sometimes I got a 404 word not found error. I'm trying to implement a try/catch that will loop back to the random word api and try again. I have two problems: 1. the try catch isnt working. 2. I have no clue how to loop back (maybe a goto)? here is my code:

void Start()
    {
        HttpWebRequest randrequest = (HttpWebRequest)WebRequest.Create("https://random-word-api.herokuapp.com/word");
        HttpWebResponse randresponse = (HttpWebResponse)randrequest.GetResponse();
        StreamReader randreader = new StreamReader(randresponse.GetResponseStream());
        string randjson = randreader.ReadToEnd();
        List<string> randresult = JsonConvert.DeserializeObject<List<string>>(randjson);
        randword = randresult[0];

        try
        {
           request = (HttpWebRequest)WebRequest.Create("https://api.dictionaryapi.dev/api/v2/entries/en/" + randword);
        }catch(WebException)
        {
            Debug.Log("error");
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string json = reader.ReadToEnd();
        List<Root> result = JsonConvert.DeserializeObject<List<Root>>(json);
        defText.text = result[0].meanings[0].definitions[0].definition;
    }```
dense cypress
mental rover
# dense cypress will this create much additional overhead?

depends on what you're doing in the initialisation - if this is some class that's setting up a bunch of arrays, meshes, etc in its constructor, and you're going to do that generation again when you grab one from the pool, then pooling isn't going to help with that much

you want to do the expensive stuff once, in the constructor, and the initialisation, i.e assignment of values or populating existing arrays of a pooled object, in another method that you can call after grabbing it from the pool

ancient cloak
#

i would recommend setting up your API to return alternative words. but you could just put your request in a do/while(response.result != success)

hot yacht
#

hello i want to ask for opinion regarding Task, is it good to place 3 Task method and Cancelation token on update?
for example

private Task updateRoom
private CancellationTokenSource roomDetail

private void Update()
{
  // There will be three of this. 
  if(updateRoom is null || updateRoom.IsCompleted)
  {
    updateRoom = GetRoom(roomDetail = new CancellationTokenSource())
  }
}

private async GetRoom(CancellationTokenSource cancellationToken)
{
  // Call API
  // Doing some stuff, like checking if user in room or set image for user if they in room or not. etc
}

This will be on mobile phone, is there will be any performance issue in here?

ancient cloak
#

no clue what updateroom is

#

so couldn't tell ya

#

but you're going to fire off GetRoom every single frame until the first one returns. that's how async works

#

not to mention your code won't compile

hot yacht
ancient cloak
#

you're using async improperly

#

if you're assigning the result you want your calling code to "await" the async method, which you can't use in unity lifecycle methods. you're better off using a coroutine if you want it to be fired in update

hot yacht
# ancient cloak you're using async improperly

errrm but what happen if just do this?

private Task updateRoom
private CancellationTokenSource roomDetail

private void Update()
{
  RefreshRoom();
}

private async void RefreshRoom()
{
    // There will be three of this. 
  if(updateRoom is null || updateRoom.IsCompleted)
  {
    await (updateRoom = GetRoom(roomDetail = new CancellationTokenSource()));
  }
}

private async GetRoom(CancellationTokenSource cancellationToken)
{
  // Call API
  // Doing some stuff, like checking if user in room or set image for user if they in room or not. etc
}

this could works too right?

ancient cloak
#

you gotta understand what async actually means i think

hot yacht
ancient cloak
#

so those black liines are your calls to refresh room happening every frame. meanwhile updateRoom still has no value

#

eventually the first thread will complete and assign updateRoom to something, but you still have n threads running that are doing the exact same thing because they were fired when updateRoom still had no value

#

because even though RefreshRoom is async, your calling code isn't awaiting it. because Update can't be async because it's running on the main thread

hot yacht
ancient cloak
#

thats' why i say you should use a coroutine. it runs on the main thread but you're able to yield to the main process

hasty haven
#

I've been trying to use OnMouseOver() for a collider for some 3d ui elements on their own layer, however with how layers are set up, things will often obstruct the mouse call.
Is there a way to do this on a specific layer or should I just use raycasts from the screen position for the 3d UI layer?

#

Just adding a simple click-to-rotate model feature, it works fine on a blank scene with no obstructions but since its spawned on its own layer, cant guarantee there wont be obstructions

#
    void OnMouseOver() {
        if(customizeGui && Input.GetKeyDown(KeyCode.Mouse0)) {
            customizeGui.StartModelDrag();
        }
    }
#

I think it would be wasteful to do repeated raycasts so maybe wait for input down in Update() then cast it

cursive talon
#

iirc its possible to define specific operator behaviour for classes
for example to define the sum of two instances of class A in the following example

class A {
    // <-- There should be an operator definition here
    public int Data;
}

class B {
    public A a1, a2;

    public A foo() {
        a1.Data = 1;
        a2.Data = 2
        return a1 + a2; // <-- The operator should work in such a way that this results in the sum of the Data fields
    }
}```
this is not a problem of defining casts, i know how to do that.
problem is i cant remember the name of defining such an operator so i cant really look it up.
any idea what this is called again? or am i completely mistaking and this is not possible
cursive talon
#

yes thank you, dont know why i couldnt find that

hasty haven
#

Np, its not a unity-specific thing since a lot of languages allow doing that

knotty sun
cursive talon
#

ok good point xD

knotty sun
#

you cannot do this

 UIManager UIM = new UIManager();

on a Monobehaviour class

dusk apex
#

Or reference the proper way instead of static etc unless it's meant to be s Singleton.

knotty sun
#

no, a Monobehaviour is a component, so add it in the gameobjects inspector then use GetComponent to reference it

dusk apex
#

Use instantiate then

knotty sun
#

it looks like you have totally misunderstood the singleton pattern

#

you want simple or you want correct?

#

simple is easy,
drop the : Monobehaviour from the class declaration of UIManager and make it static

#

correct is more complicated, read up on using the singleton pattern

grim marlin
#

Is it possible to do a playerInput manager in Unity that call corresponding script/action when needed ?

#

And would it make sens to do so

knotty sun
hasty haven
#

SIngleton pattern is really useful if you dont overdo it.
Can be really useful in multiplayer games for referencing a player roster

#

Can also spawn a GUI separately from the player and link the player up to it from a singleton

humble kraken
#

I am making a component-based spell system. The idea is that I have a list or behaviours and I mix and match these behaviours. These behaviours are executed OnSpellStart. My question is how can I make a timer behaviour, where I can have a behaviour that sets a timer, for example, for 1 min and then the next behaviour executes ones the timer expire?

swift falcon
#

Hey so in C++ it's possible to push values to a variable from a string, I'm trying to parse a file format and one section in the file is formatted as follows:

[ 0 1 0 0 ] [ 0 0 -1 0 ] 0 1 1

If I was using C, I'd be able to use

printf("[%f %f %f %f] [%f %f %f %f]\n%f %f %f\n\n", VARIABLES TO ASSIGN HERE);

Could I potentially do the same in C# in some way?

cerulean mist
#

Hi everyone. I am awful with Quaternions! Basically, I am spawning a blood splatter decal on the floor which is supposed to face away from the player. I am using Quaternion.FromToRotation to get it on the ground, now I just need to rotate it towards the player. Any ideas?

Here's a picture demonstration. The red box outline represents the enemy, the black line representing the bullet, and the decal which is pointing away from the player

        if(Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 10)) {

            GameObject decal = GameManager.Instance.SplatterPool.SpawnDecal(new Vector3(hit.point.x, hit.point.y + 0.01f, hit.point.z), Quaternion.identity);
            //decal.transform.rotation = Quaternion.LookRotation(from.transform.position);
            decal.transform.rotation = Quaternion.FromToRotation(-Vector3.forward, hit.normal);
        }```
stuck cobalt
#

Hello, so I was wondering maybe someone could help me :
I just checked a video on FiniteStateMachine where you create new class that doesn't inherit from monobehaviour to partition states of a GameObject for example. The only problem is that i usually use a lot of references in my classes from other scripts i wrote and i use the inspector or some monobehaviour methods to get the references. With a script outside of monobehaviour i don't know how to do it. Thx

prime sinew
prime sinew
# stuck cobalt Hello, so I was wondering maybe someone could help me : I just checked a video o...

Building a Finite State Machine | Unity Tutorial
Game Development Course by Roundbeargames

  • we'll be using the finite state machine for all our future animations
  • this video is about laying the foundation so that all the characters can be organized and managed

Files are available here:
https://drive.google.com/drive/folders/17Lfpa5r-3zeR1jaT0...

▶ Play video
#

you should just be clear on what the class inherits from if it's not monobehaviour

hasty haven
#

Is there a reason I'm getting hits from objects from other layers with RaycastNonAlloc?
Sensormask is set to only include one specific layer but i'm getting results from others as well.

    void CheckForMouseOver() {
        if(!customizeGui || !cam) return;

        ray = cam.ScreenPointToRay(Input.mousePosition);
        int numHits = Physics.RaycastNonAlloc(ray, hits, 20f, sensorMask);
        for(int i=0; i<numHits; i++) {
            Debug.Log(hits[i].transform.gameObject);

            // If hit self, start dragging
            if(hits[i].transform.gameObject == gameObject) {
                customizeGui.StartModelDrag();
                return;
            }
        }
    }
wild vigil
#

How would I create and save a scriptableobject from my editorwindow?

#
    {
        ScriptableObjectList newItem = ScriptableObject.CreateInstance<ScriptableObjectList>();
        newItem.prefabName = "name";
        AssetDatabase.CreateAsset(newItem, "../Data/"+newItem.prefabName+".asset");
    }```
knotty sun
#

normally you would add a MenuItem attribute

wild vigil
#

I want to handle it through my editor

hasty haven
#

You can right click -> create and see it

#

menuName is what it looks like on the drop down menu

#

and filename is the default name when you make one before typing it in

toxic notch
#

This triggers error: KeyNotFoundException the given key was not present in the dictionary. Any ideas why this is?
if (hitMaterial != null || bulletImpactDictionary.ContainsKey(hitMaterial))

knotty sun
wild vigil
# hasty haven

Thanks, but this is not the way I would like to do this.

mellow sigil
toxic notch
#

ya really though containsKey should handle null cases

prime sinew
knotty sun
#

no, dictionary cannot have a null key value

toxic notch
#

Ok not sure what would cause the not present then

#

That is the offending line

knotty sun
#

it should generate an invalid key exception rather than a not present exception

toxic notch
#

I've basically got a collision on a bullet: ```
void OnCollisionEnter(Collision collision)
{
Debug.Log("bullet collision " + collision.gameObject.name);
ContactPoint contact = collision.GetContact(0);

        if(collision.gameObject.TryGetComponent<Renderer>(out Renderer renderer))
        {
            BulletImpactManager.Instance.SpawnBulletImpact(contact.point, contact.normal, renderer.sharedMaterial);
        } else
        {
            BulletImpactManager.Instance.SpawnBulletImpact(contact.point, contact.normal, null);
        }
then in that method: ```
public void SpawnBulletImpact(Vector3 position, Vector3 forward, Material hitMaterial)
        {            
            if (hitMaterial != null && bulletImpactDictionary.ContainsKey(hitMaterial))
            {
                DoSpawnBulletImpact(position, forward, bulletImpactDictionary[hitMaterial].GetObject());
            } else
            {
                //could do a default material but hold off for now
            }
        }
#

I dont get why it's generating an exception at all

#

Docs say it returns true if found, false if not

hexed pecan
#

Maybe BulletImpactManager.Instance is null

#

Or the dictionary

knotty sun
#

that would be null ref not a Not present

hexed pecan
#

Oh right, I didnt read above, just assumed NRE

knotty sun
#

this
bulletImpactDictionary[hitMaterial]
this the only thing that should generate a not present

#

but with the if that should not happen

toxic notch
#

I just restarted it and am not seeing it triggered anymore

#

Not sure what condition is causing it

knotty sun
#

I think it was the difference between || and &&

toxic notch
#

Riiiight

#

that makes sense

#

Thanks guys

smoky crag
#

I'm trying to get an enemy to charge at the player by setting their velocity to the player's direction but sometimes the number goes into scientific notation and the enemy won't move

Does anyone have an idea how to fix this bc I'm out of ideas

rain minnow
indigo drift
#

Can you edit Unity Events via code or just the inspector?

potent sleet
#

you can assign them in inspector sure

indigo drift
hidden compass
#

i got tutored on how to add unityevents in code

#

this is my shat little example

indigo drift
#

I don't know how to change unity events through a script or if you even can do that so that's what I'm asking

indigo drift
#

Ooooh, are the listeners the methods in the event that are called?

hidden compass
sudden meadow
#

any clue what's missing when compute shaders wont trigger the intellisense?

#

tried deleting the .sln

autumn cipher
#
public class Player : MonoBehaviour, IDamagable
{
    public static Player player;
    void Awake()
    {
      player = this;
    }
}```
This is probably not good for making a multiplayer game, is it?
#

I got many classes related to Player (Movement, Weapon System and so on), I don't want to create a Player reference on each of those classes

#

do I have to or is there another way?

hidden compass
#

dont think so, only 1 static can exist, 2 players mean u'll end up having 2 player scripts

autumn cipher
#

sorry for the beginner question

polar marten
#

you probably want to start with a tutorial or asset

hidden compass
#
Also, in a Unity multiplayer game, the same code is executed in all instances of the game (host and clients). To let the players to control only their ships, and not all ships in the game, we need to add an If condition in the beginning of the FixedUpdate method checking if this is the local player (if you’re curious on how the game would work without this If condition, try removing it. When moving a ship in a screen, all ships should move together).```
#

heres the link from the exerpt

#

has alot of good info about how ud construct a Multiplayer title

autumn cipher
autumn cipher
smoky crag
wild vigil
#

How can I destroy a scriptableobject from my editor?

plucky karma
wild vigil
#

Found it. "AssetDatabase.DeleteAsset()"

orchid bane
#

I have ContinuousDamager which has method DealDamage, event OnDamagingStarted and event OnDamagingEnded. Usually I subscribe to the first event with something like StartWork and to the second one with something like StopWork and then call DealDamage, but some ContinuousDamagers may not even fire OnDamagingStarted because of their internal preconditions, not even talking about OnDamagingEnded. Because of it I am still subscribed to the ContinuousDamager. How would I fix it?

soft shard
# orchid bane I have **ContinuousDamager** which has method **DealDamage**, event **OnDamaging...

You could maybe make a call back or store a event as a param to your "start work" or "continuous damage" functions, if the condition happens during execution, you can use that stored event to "cancel" the subscribe, with a delegate that unsubscribes as the param, or when the call back returns a certain value - I think you will need a way to detect when your condition causes your "start" to either pause or cancel, if the condition is not set in the "start" function itself - if it is, you could have thst function be a bool return and check if its false, unsubscribe then-and-there

gaunt garden
#

For the second case DeleteAsset also works fine 👍

ionic socket
#

In Order to receive EventSystem events (IPointerDown, IDropHandler, etc) a gameobject must not only implement the proper interfaces, but must have a Raycast Target like an image. Is there a way to create a general zone (say, an area to drop playing cards) that doesn't have it's own graphic attached? I can make an invisible image but that seems like a hack.

gaunt garden
ionic socket
gaunt garden
#

I don't know of one, and the raycasting code early-outs if no Graphic elements are found for the targeted canvas

#

I would just put an invisible Image there

rain minnow
fallow abyss
#

Anybody using Unity Netcode? How can I show worldspace UI only to players that triggers it?

rain minnow
clever lagoon
ionic socket
clever lagoon
#

" I can make an invisible image but that seems like a hack." Thats how I do it.

#

you CAN roll your own, and check screen position against an otherwise empty RectTransform. But meh.

ionic socket
#

like im imagining a pop-up menu on an interactable object or something?

fallow abyss
ionic socket
fallow abyss
#

Oh that makes sense. Thanks

ionic socket
#

I'm still learning, btw. I'm working off this video https://www.youtube.com/watch?v=3yuBOB3VrCk

🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle

Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubref=ngo
FREE Third Person...

▶ Play video
clever lagoon
autumn cipher
#

which one is more expensive for moving an object?
Lerping it on Update() with Time.DeltaTime
or
MovePosition() it with Rigidbody on FixedUpdate with Rigidbody's interpolation enabled

dusk apex
autumn cipher
#

yeah definitely, thanks

simple mountain
quartz folio
#

!vs

tawny elkBOT
sudden meadow
#

@simple mountain it's ok we fixed it, it was just vs not being set as the external tool so it didnt' build the proj files

rancid frost
#

what event triggers whenever you drag and drop data into a serialized field in editor?
I want to change a value in editor whenever a user changes a serialized field

fallow abyss
rancid frost
rain minnow
# clever lagoon if anyone cares, tests say: yes

I missed this but if the parameters are named with "direction" I would normalize them as a direction typically is

Thanks for the test results though. Did you try without normalizing (just to confirm)? I know some methods use or state a direction vector where all parameters don't have to be normalized . . .

buoyant crane
quartz folio
#

No memes/gifs.

rancid frost
rancid frost
clever lagoon
quartz folio
#

No idea why dyno was so slow to get that one lol, I thought it was manually posted because it didn't get it

buoyant crane
rain minnow
rancid frost
rain minnow
plucky karma
#

ScriptableObject is MonoBehaviour Wink wink 😄

rancid frost
# rain minnow That normal class must be an instance on a MonoBehaviour or ScriptableObject, no...

the class simply has 2 variables which I want to serialized
think of it like a struct

then in another class which has monobehavior, I want to use said class

Here is some code

 public class UIManager : MonoBehaviour
    {
        [SerializeField] private List<UIContainer> UIPrefabs;
          
        // I could call the validate here, but I rather note

    }

 public class UIContainer
    {
        public GameObject UIPrefab
        public UIPrefabName UIName;
    }

#

the problem with monobehavior and Scriptableobject is that I cant access those serializedfields

simple mountain
#

where is the issue, or rather how do I read that property

quartz folio
#

It's a method, not a property

#

call it properly. It returns nothing

simple mountain
#

so why is it even there

quartz folio
#

You can see its arguments in your popup, it has out parameters.

rancid frost
simple mountain
#

ou that s how it works

rancid frost
#

yes sir

#

when the function runs, your variables will be updated after

simple mountain
#

so it s basically the same as passing a refference, and changing the value of the refference to something else?

rancid frost
#

one advantage of this is that if the function fails, usually your program doesnt crash since the variables are already initialized

simple mountain
#

I don t see why that would stop crashing but it seems like really great syntax stuff

rain minnow
rancid frost
rancid frost
#

"out requires that the method accepting the parameter MUST, at some point before returning, assign a value to the variable."

simple mountain
#

well that s great so I will use out from now

#

do you know why Task.Run is so much faster than thread.start eventho from what I could see it does exactly the same?

quaint rock
#

they are not doing the same thing

#

Task.Run heavily depends on how things are setup for how it will work but generally it gets a existing thread from a pool to use but what it does depends on how the sceduler is setup

scenic creek
#

How can I have a vector that is clamped in magnitude, but can be greater in some directions? I want my player to have a greater forward max velocity than backward. On a graph the max speed would look something like this. Sorry for bad drawing, I'm using trackpad.

hexed pecan
quaint rock
#

would just keep it normalized, scale it larger when going forward

#

the dot product is a great idea too, since you can more or less make a mask for each direction with it

wicked river
#

Hey! I have two scenes. and a button that changes from scene one to scene two. How can I set the position the player needs to spawn at when scene two is loaded ?
I feel it should be as easy as setting an empty gameObject in Scene two and getting it's transform.position and just using that, however I am not sure how I can reference other scene gameObjects in my scene one

scenic creek
#

I know what dot product is and lerp, but I don't understand what you mean to use them together.

gaunt garden
#

This would give you twice your vector when directly going up, and less as you start to deviate from the up vector

scenic creek
#

Wouldn't this give zero if going backward, so it would just nullify it instead of adding backward?

hexed pecan
#

No.

#

it is myVector PLUS extra

#

if facing forward

scenic creek
#

dot product of (0, -1) and (0, 1) is -1, which gets clamped to zero. whatever myVector is * 0 will be 0.

hexed pecan
scenic creek
#

ok, so this sort of decomposes the vector2 into just the forward part, then only modifies that part.

hexed pecan
#

Hmm yeah

#

Base vector + forward

scenic creek
#

ok I think this works for me. Thanks.

rain minnow
#

The clamp will return 1 when facing forward and 0 when facing backward. Then you add your magnitude vector of 1, so if facing forward it becomes 2 and if facing backward it becomes 1 . . .

scenic creek
#

If I want forward and sides and back to all be different strengths I would have to divide the whole thing by two then multiply by how powerful I want it to be right, so if I want forward to be clamped to 1.5 then it would look like

((myVector + myVector * clamp(dot(myVector, Vector.up), 0, 1)) / 2) * 1.5
#

except I have to use myVector.normalized inside the dot product.

quaint rock
#

think people assumed it was normalized from the start

rain minnow
#

You said your vector was clamped in magnitude, that sounds like it's normalized already . . .

scenic creek
#

Yeah, I don't want it normalized though because if the player is using controller, then input coming from a stick might be inside unit circle.

#

clamped just means its between two values. normalized means its magnitude is definitely 1.

#

Also the vector doesn't start clamped. The question is how can I clamp it, but not in a circle.

rain minnow
#

Earlier, they provided a result for front/back. You'll need another solution for left/right if you want it to be different . . .

scenic creek
#

Yeah, here's what I have now.

input = ((input + input * Mathf.Clamp01(Vector2.Dot(Vector2.up, input.normalized))) / 2) * forwardSpeed;
input = ((input + input * Mathf.Clamp01(Vector2.Dot(Vector2.down, input.normalized))) / 2) * backSpeed;
input = ((input + input * Mathf.Clamp01(Vector2.Dot(Vector2.left, input.normalized))) / 2) * sideSpeed;
input = ((input + input * Mathf.Clamp01(Vector2.Dot(Vector2.right, input.normalized))) / 2) * sideSpeed;
#

Oh i just realized something wrong lol

#

I think I should be multiplying the input by forwardSpeed before adding it.

spare otter
#

Why is my public bool isn't referenced in the unity script interface ?

scenic creek
spare otter
scenic creek
#

And no compiler errors

spare otter
inland python
#

is there a way to force unity to not save playerprefs on application quit?

quaint rock
#

this sounds like a XY problem

#

why are you putting stuff in it you do not want saved?

#

or if you need more control over saving why are you even using player prefs?

inland python
#

i was just curious if i could nevermind

toxic notch
#

Why would a collision be read between the gun and the bullet here? There is no overlap of colliders?

thick gale
#

sorry misread the first time, is that where it gets instantiated?

toxic notch
#

Yes

#

I did a getTag on instantiation and found the gun, then got all colliders and ignored collision on them and that worked

#

still not sure why it would trigger though

hexed pecan
#

Which one it hits

rain minnow
pine schooner
#

I have a quiz game that every question (same scene and panel) changes the text and buttons, and I want to change the "pressed color " to green when it is the correct button, how could I do that?

quaint rock
#

Button has a property called SpriteState on it

#

you create a new one where its green for pressed and set it on the button

pine schooner
#

ty

#

i'll try

proud juniper
#

do all of the IEventSystemHandlers (IPointerDownHandler, etc) function the same in the new input system versus legacy input system?

quaint rock
#

iirc they do

#

but you need some more setup for the new input system

proud juniper
#

They seem to, so far, but I don't want to assume.

#

I may need to start checking which action map is active I suppose

quaint rock
#

i have not seen otherwise and recently ported a large project to the new input system since it was easier for me to add controller support with it

proud juniper
#

it also seems like it's easier to manage different game states with it by switching maps

thick gale
#

can you save a list of bools to json? or no

quaint rock
#

json supports bools and lists just fine

thick gale
#

alrighty, i need to review my code then haha

rigid island
#

Hey I have a list of Vector3Int, I am trying to do a while loop to add to this list random points only if the points are not the same points or the distance is less than < 2. Any help would be appreciated

#

I can show code what I have so far if it helps, the struggle is doing a foreach loop in a while loop

somber nacelle
#

what do you mean by "the distance is less than 2". like the distance from any point within the list? or do you mean from a specific point, if it's the latter just use a HashSet instead of a List and you'll never have duplicated entries

rigid island
#

tried to foreach through the growing list of random points but compiler yells at me

somber nacelle
#

you can use the Any method from linq to see if any of the objects in the list meet the condition

rigid island
#

yes I thought of linq I just not sure how to put that together in my while loop

#

let me show my horrible code so far one sec

#
 Vector3Int lastPos = Vector3Int.zero;
        while (randomMidPoints.Count  < pathPerSide)
        {
            var r = Random.Range(0, midTiles.Count);
            var currentPos = midTiles[r];

            Debug.Log($"Current Pos {currentPos}");

            if(randomMidPoints.Count > 0)
            {

                foreach (var pos in randomMidPoints)
                {
                    Debug.Log($"Last Pos {pos}");
                    if (currentPos != pos && Vector3Int.Distance(pos, currentPos) > minDistance)
                    {
                        lastPos = currentPos;
                        Debug.Log($"Last Pos {lastPos}");
                        randomMidPoints.Add(midTiles[r]);
                        GB.SetTile(midTiles[r], debugTileB);
                    }
                    else
                    {
                        Debug.Break();
                    }
                }
            }
            else
            {
                if (lastPos != currentPos)
                {
                    Debug.Log("sup");
                    lastPos = midTiles[r];
                    randomMidPoints.Add(midTiles[r]);
                    GB.SetTile(midTiles[r], debugTileB);
                }
            }```
#

the issue with this was iterating a foreach through growing list

#

aside from the horrible code

somber nacelle
#

if(randomMidPoints.Any(x => x != currentPos && Vector3Int.Distance(x,currentPos)))
would replace inner foreach loop and condition

rigid island
#

awesome!
let me give that a try

quaint rock
#

also why Debug.Break

rigid island
#

desperation

#

I normally put breakpoints and step through code

quaint rock
#

Debug.Break just pasues unity

somber nacelle
somber nacelle
#

take a look at where that error is and see if you can figure out what is wrong with it

quaint rock
#

its from the code you suggested

#

not comparing the distance to anything

somber nacelle
#

i know, and i know exactly what is wrong with it too

rigid island
#

Sorry this is like my second time using linq lol

somber nacelle
#

it's not an issue with linq

#

it's the condition

#

hint: one of the two conditions isn't actually a condition because it returns a float rather than a bool.

rigid island
#

oops

#

thanks needed the > 2

rigid island
#

dang

somber nacelle
#

you removed the foreach, right?

rigid island
#

ye

somber nacelle
#

show the current code

rigid island
rigid island
#

i didnt save it

#

Thank you!

#

oh its no error but doesn't work @somber nacelle

somber nacelle
#

i assume by "doesn't work" you mean it is still adding duplicates to the list in which case ^

rigid island
somber nacelle
#

and that if statement checks if any point is less than 2 units distance so what do you think you could do there?

#

wait, actually you wrote the condition so it checks if any point is greater than 2, but you should check if any point is less than and invert the condition

rigid island
#

gotta force close

somber nacelle
#

you'll have to share the current code if you want help with it

#

but you don't really do anything to handle if none of the points in that midPoint collection meet your conditions for being added to the set

rigid island
# somber nacelle but you don't really do anything to handle if none of the points in that midPoin...

This is after I switched the <

Vector3Int lastPos = Vector3Int.zero;
        while (randomMidPoints.Count  < pathPerSide)
        {
            var r = Random.Range(0, midTiles.Count);
            var currentPos = midTiles[r];

            Debug.Log($"Current Pos {currentPos}");

            if(randomMidPoints.Count > 0)
            {
                if (randomMidPoints.Any(x => x != currentPos && Vector3Int.Distance(x, currentPos) < 2))
                {
                    lastPos = midTiles[r];
                    randomMidPoints.Add(midTiles[r]);
                    GB.SetTile(midTiles[r], debugTileB);
                }
            }
            else
            {
                Debug.Log("sup");
                lastPos = midTiles[r];
                randomMidPoints.Add(midTiles[r]);
                GB.SetTile(midTiles[r], debugTileB);
            }```
somber nacelle
#

you forgot to invert the bool returned by Any

#

but you're still not handling cases where none of the points in the collection meet the conditions specified

rigid island
somber nacelle
#

yeah because then if any objects in the collection have a distance of less than 2 it will fail the condition as you implied you wanted

rigid island
#

I would like the while loop to keep trying

#

until it is met and filled with let's say 3

somber nacelle
#

right, that won't break the loop, it just moves on to the next iteration

#

but you're not handling cases where the collection you are getting random objects from does not have enough elements that satisfy the condition you are checking to end the while loop

#

a quick/dirty way to do that would be to count how many times you have looped and if it passes some arbitrary number it breaks the loop (and probably logs info)

rigid island
#

Just need 2 spawn points to never be close to any other spawn points. I think my approach was already doing too much there may be a while to baypass it or no

astral oriole
#

my controls somehow got turned into a visual studio's file, how do i change it back to an inputactions file?

rigid island
#

I need the list of v3 though because of the tilemap coords

somber nacelle
somber nacelle
astral oriole
#

sry

somber nacelle
#

also not a code question anyway

ancient cloak
low nymph
#

how could i get it so when you shoot a tank it moves the tank back a bit

ancient cloak
#

is your tank using a non kinematic rigidbody

low nymph
#

yes

ancient cloak
#

then simply add a force

low nymph
#

would adding a force just be attaching a empty game object to the cannon then passing it in as the vector 3

merry ridge
#

Hey brothers. I'm programming a 3d game. Does anybody know the best way to rotate a character so they only face the 4 cardinal directions? The foloowing code is what i use to rotate my character using a character controller and the new input system.

Vector3 rotationVector = new(moveAction.ReadValue<Vector2>().x, 0, moveAction.ReadValue<Vector2>().y);
if (rotationVector != Vector3.zero)
{
                Quaternion toRotation = Quaternion.LookRotation(rotationVector, Vector3.up);
                directionArrow.transform.rotation = Quaternion.RotateTowards(directionArrow.transform.rotation, toRotation, float.MaxValue);
}

This works well, the only problem is that it allows the player, at least when using keyboard, face the ordinal directions. Anybody know any doe i could introduce that forces the player to only face the cardinal directions? Should i just drop the code above?

rigid island
#

😫 fuckin lists and linq ... whyy so painfull..

quaint rock
#

its meant to be a tool to help, if you find it harder to understand linq just use loops

rigid island
#

I did try that but it gave me an error that wasn't able to iterate through a collection that grows :\

quaint rock
#

unless you are doing a while loop

hallow quest
#

Hey guys, I'm seeing some strange behavior in my game. I'm getting different behavior on windows(gif) VS android(mp4).

I've included the codeblock in question

rigid island
#

while was just doing retries but I had a foreach that kept being added to each while iteration

#
 if (!randomMidPoints.Any(x => x != currentPos && Vector3Int.Distance(x, currentPos) < 2 ))
                {
                    currentPos = midTiles[r];
                    randomMidPoints.Add(midTiles[r]);
                    GB.SetTile(midTiles[r], debugTileB);
                    Debug.Log("Hello there");
                }``` this works but it doesn't account for Distance for some reason
dusk apex
quaint rock
low nymph
#

how should i calculate the direction to knock the player back, im thinking this.transform.position - endOfBarrel.transform.position

rigid island
#

wait this kind of does work I think If I put <=

#

if (!randomMidPoints.Any(x => x != currentPos && Vector3Int.Distance(x, currentPos) < =2 ))

#

but it's still adding duplicates I think

#

yup

somber nacelle
#

get rid of the first part of the condition inside the Any call

rigid island
#

do you mean x != currentPos

somber nacelle
#

yes

rigid island
#

what do I put instead to not get duplicates

somber nacelle
#

nothing

#

if it is the same point the distance would be 0

rigid island
#

I think....that...worked..

#

holy mushrooms!

#

@somber nacelle thanks alot! you saved me days of heartache fr

#

ty

covert turret
#

I'm looking into template programming in C# right now, I understand the statically declared use of Func<T> and delegate T fooFunction(T foo1, T foo2) but how do I make it so that I can pass any amount of parameters?

#

googling just comes up a mess of either the former or latter

hallow quest
quaint rock
#

T fooFunction<T>(params t[] items)

#

also @covert turret C# has not templates its generics that do this which are more limited then C++ style templates

covert turret
#

yeah I was afraid that was the case, all good, thanks for helping clear that out

#

i'll make do with these

low nymph
#

is there a way to amplify addforce

somber nacelle
#

wdym by "amplify"?

quaint rock
#

multiply your vector by a bigger number

low nymph
#

ight

somber nacelle
#

i'd bet the issue is that they aren't using ForceMode.Impulse considering earlier they wanted a knockback for a tank or whatever. of course, until they explain we have no way of knowing which they need to do

low nymph
#

im using impulse but its still too little

somber nacelle
#

then yeah, use a bigger amount of force

#

or you are overriding it by assigning velocity every frame

low nymph
#

multiplying it did the trick

somber nacelle
#

do you use velocity for movement?

#

or do you actually use AddForce for regular movement?

low nymph
#

addforce for regular movement

potent sleet
low nymph
#

how would i rotate the tank cannon bone to the direction the player double taps (for a dash)