#archived-code-general
1 messages · Page 20 of 1
Are you using VS as your git client?
yessir
basically you can just check git status with any other git client
but it's unlikely git would be confused
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
file -> save project in unity
thanks, was able to get it to save by adding an item to list
saving
then removing from list
and saving
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?
set up layer based collisions in physics settings
Does anyone know how to add bloom effect to a singular game object?
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
It works thanks
What's a buffer🤣
really only a easy thing if you already know how render features work or have wrote post processing effects
I'm basically a fresh beginner at unity, I'm not really sure about any of that, how would I learn about it?
Unity's YouTube channel has a pretty nice playlist for "tutorial for beginners"
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)
if what doesn't exist
what is Armor?
what is spriteCollection
sorry yeah that might be important
its a SO with Armor category and this inside it
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?
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;
}
}
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
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
could just set a bool when you dash
and only allow keystrokes when not dash
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
If I have something like
_event += M1;
_event += M2;
M1() => _event -= M2;
M2() => Debug.Log(1);
Will I never have the debug?
I don't think so, but it's easy to test.
Just tested, somehow both are called
@late lion you tend to be awesome at programming...any chance you know how to do this 😄
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...
thanks
vector3.forward is for 3D
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.
I suspect what you want is:
item.ID = spriteCollection.Armor.First(i => i.Name == item.ID).Id;
But technically your foreach does it for each element that matches, so only the last element actually sticks.
ah first instead of single
there should only be 1 instance...or 0 instances
where there were 0 it was erroring which was the issue
Idk when I use linq it NEVER works
throws error on no matching element so not quite what I was looking for 🙂
Would you want barriers_perimiter_outer_fence and barriersperimiterouterfence to end up with the same distance? Would you want that score be smaller than just fence or outerfence, for example?
Removing the underscores would increase the score slightly, so I thing barriersperimiterouterfence would be closer. I think I'd want something shorter to have a higher score than something longer containing a string similar to the search query
I don't think there's a one-liner for this. If you want the exact equivalent to your foreach, it would be:
var match = spriteCollection.Armor.LastOrDefault(i => i.Name == item.ID);
if (match != null)
{
item.ID = match.Id;
}
fair enough thanks 🙂
figured idk how linq works so there was probably a way to do it in 1 line
I wish I could just use this editor space function in a build
https://docs.unity3d.com/ScriptReference/Search.FuzzySearch.html
Annoyingly makes it hard to find a library that does this because "Unity FuzzySearch Library" just keeps bringing this back up
What about "C# fuzzy search library"? This comes up:
https://github.com/JakeBayer/FuzzySharp
But I'm surprised there aren't more libraries for something like this.
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
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)
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
MIT License on GitHub, so you should be good
Should be able to open it in 7-Zip or WinRAR
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
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.
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
enemy.InverseTransformDirection(player.forward)
How would i go about making a script that choose 1 random animation to play ?
you can start by looking up
- how to play an animation through code
- how to randomise a number
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?
why not? i dont think OnEnable would be an issue
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..?
oh. maybe.. all i do know is coroutines stop when the object is disabled
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
I'm afraid you might be more informed than I am on this, so I dont think i can help
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.
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
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?
print out all the values of PosHistory to see if they are all the same value
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?
@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.
Not really for this situation.. it's sort of a rudimentary queue animation.. or .. FSM animation, perhaps
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...
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
any1 know any good scripts for dynamic 2d movement i want something that feels clean
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);
}
}```
thanks, but now it's giving me this error: WebException: The remote server returned an error: (403) Forbidden.
does it havbe something to do with my api key?
ok i'll look into it :)
https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
Is there a way to combine more than 1 condition and using an enum value as a condition?
I want to use multiple enum values as a condition
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;
}
thanks!
hadn't considered that
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
@thick socket , not sure if you saw my console readout? https://cdn.discordapp.com/attachments/763495187787677697/1066071270543855687/image.png
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.
no clue then man
seeing code helps a lot
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?
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
idk if you already know this
but if you lock the inspector
you can do that
can click like 3 things and drag them all in at once
oh. my. god.
ikr
yeah np!
¯_(ツ)_/¯
🙏
Thanks anyhow.
That's the thing though. After it's spawned in there is no code. It's literally just a 3D cube set to be a child of the car. That's it
I mean, the cars movement is probably a script?
but if its not really script related I would move to #💻┃unity-talk
they may have a better idea there if its a rigid body issue
Yeah, the only script on the car itself is that it's adding a torque based on horizontal axis and a force based on vertical axis
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
yes how do i reference the current index of the array?
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
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?
are you looping through the array?
in your for loop: for(i = 0; I < array.Length; i++) { blah... } "i" (or whatever you name it) is the index. If you're using a Foreach on a List, you can YourList.IndexOf(value) but it will return the first index if there are multiple entries with the same value.
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
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
what do you mean
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?
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);
}
}
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.
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?
Ngl, that sounds a bit unoptimized (considering that the spawner has to check every frame), but I'm a newbie on this so I can't give a better solution unfortunately.
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
why on the connection approval example it uses ConnectionApprovalResponse member variable "Reason" which does not exist for that class?
anyone know how to render just part of a render texture onto a raw image?
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
_animator.SetLayerWeight(1, Mathf.Lerp(_animator.GetLayerWeight(1), 0f, Time.deltaTime * 13f));
--> Time.deltaTime * 13f // This value indicates how fast the transition does ?
you could use the Tiling and offset of the UV rect on the raw image to select what part you want to reender
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?
have u coded that in @celest condor
I just built the game again and the problem is fixed
Unity moment lol
Thanks anyway tho
vertices are in local space
If you wanted to get them in world space you would have to transform them https://docs.unity3d.com/ScriptReference/Transform.TransformPoint.html
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
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);```
Could anyone help me find a bug in a movement code?
The code is bit longer though
Nevermind. I figured it out
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
links are pinned in #💻┃unity-talk
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
can you not do a DateTime.Now.ToString("MMM. dd yyyy").ToUpper() ?
Oh that worked, honestly I never used the format parameter thing for ToString so didn't know you could combine them
thanks!
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
How do i make the lightning dark?
lower the intensity of your light object
but im using the first person template
nvm got a effect i like
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.
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
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?
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
You are 100% correct, but sometimes you just prefer a public variable over a property even though it is almost always better to use a private variable exposed to other objects through a public property.
You can also ignore what that other person said about making it public to set it in the inspector since you can use the [SerializeField] attribute to expose a non public field to the inspector
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
where do you store the slot data
ggamemanager.slots
never mind, i'm confused
ohh u mean the drop handler??
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?
u want the github link
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?
my repo
so what do you want to do, and what isn't working?
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??
okay, so what's the trouble here
soo the trouble is it dosent call ondrop when the slot is occupied so i need to detect in onendrag
i dont see an ondrop anywhere
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 ^
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
what I mean is, put this script on an image that's above everything else in the slot, including blocks
no it is on the slot itself
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
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
show how you're making the gameobject detect a click?
we'll need to see where you called that code
that code alone seems fine
!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.
but I can see you're using OnMouseDown
that's all I really needed to know
OnMouseDown requires a collider on the object
Is there any way to change lang version to C# 9 on unity < 2021?
everything works expect the Z position update
technically you can upgrade the roslyn compiler, but it's not recommended. why not just update to 2021 if you want to use c# 9 features?
line 32
look at line 37
I can't update it due to internal issues, how would I update the roslyn for Unity?
lol "internal issues" prevent you from updating the editor, but not bastardizing the editor to do what a more recent version would do anyway?
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 🤷♂️
Seeing this as a general for coding - Has anyone seen that ProgrammerHumor posting about Dutch's open source government tool on loading bars?
Alright, will try my best to break it then
the cluster of if statements? it's honestly not a terrible way to handle that, it's super readable which is the main benefit and not really any slower than the alternatives
Made a version in rust lang 😄
at what point should a script be broken up into multiple? How often does too much stuff being in one code cause issues?
keep your classes to a single responsibility. once you start making it do a thing unrelated to its original purpose is when you split it up
when a class does too much, it becomes harder to debug as well as to maintain
simple enough, appreciate the insight
Solved, just in case anyone wondering -> https://github.com/mob-sakai/CSharpCompilerSettingsForUnity
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 😅
uint and int take the same amount of memory. Just that since uint doesnt consider negative values, it can go to higher positive values
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
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);
}
Tldr: it doesnt matter. One point tho is that you should stick with one type in your code as int + uint for example is not possible without conversion
@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..
you could use a property to help you handle that
@prime sinew Like [Min(0)] you mean?
uh no, like a custom getter/setter
@prime sinew Ah, yeah not a bad idea I guess.
can someone help me with this??
I am trying to take a class object
{
"name": "poker",
"email": "poker@poker.com",
"id": 1
}
this is what I am trying to get and this is how I made the class (I tried using id as a string or int)
public class Deserialized
{
public string name;
public string email;
public int id;
}
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?
Resources.Load absolutely does work in a build. obviously AssetDatabase won't. but your other options are addressables, or direct references
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
as long as you follow the law of the Resources folder it should work just fine
Every force has an equal yet opposite force acting against it?
the objects loaded using the Resources class must be within a folder named Resources
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?
also, literally first result on google: https://answers.unity.com/questions/288948/rotate-around-local-y-axis.html
there's also just Transform.Rotate with the Space parameter
so something like this should work? and its gonna ignore all the .meta files?
it will not load meta files, correct
woo danke danke
also don't include the extension in the path
on it boss!
Sorry, I don't have a transform to work with. Its just a point and a rotation value.
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
Yeah, I guess I could have worded it better. Your response was pretty snarky as well. rough day?
well the actual question you did ask was easily googleable, notice how i provided 3 pieces of information all super quick like that?
;-; 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!!
Nah, nothing to see here.
I worked it out. Just needed to convert my raycast normal into a quaternion and multiply by another quaternion for the rotation.
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);
Deserialization cannot occur before a constructor
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
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
@quartz folio @ancient cloak I see. So no constructor use when using MonoBehaviour basically.
Generally not advised
@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.. 🤔
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
also if you're instantiating scripts via script you shouldn't construct them, you should use GameObject.Instantiate
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 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..
oh i wasn't sure since you were constructing the script
Why are you initialising them via code
looks the same to me. Amy way to turn off the gizmos in scene view?
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 
@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.
private void Awake()
{
_playerInventory = new PlayerInventory(this);
}
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
there's also a design consideration of - why does your inventory need to know how the player uses an item?
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
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
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;
}
IMO your inventory should only be responsible for things that an inventory does. not what things do with the items in an inventory
But none of those things are UnityEngine.Object types
So that constraint makes no sense
Because the item is in the inventory, makes more sense to have it there than the PlayerController I would say. I have a general class that handles the storage (add, delete, find etc) that can be applied to other things that isn't the player's inventory, such as a storage chest or whatever you can think of.
That's why I'm asking. Is there a way to do it.
The convention says generic types should start with T
So you would return T and cast what you return
@sour trench but why does the inventory need to tell the player how to use an item
The point was it was not accomplishing what I wanted it too. I found "Tool.current = Tool.none;" Only issue now is that I only want the tool off for one object in the scene, not all of them.
why can't the player just take an item from the inventory
@ancient cloak You mean when I click an item in my inventory, why the UI script doesn't just call Use directly?
sort of, but it's not clear why you'd want to - seems you'd end up in a mess of branching and casting where you check each type explicitly anyway
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
An idea how to be able to add muscle growth to my character?
@dense hamlet Protein powder and lots of hard work.
Use shapekeys/morphtargets
It's because each item has its own method that determines what it does. And if it doesn't have a reference to the character that uses the item, how can it apply the effect?
could also blend in a normal map that shows muscle definition.
that's potentially valid, but there's no reason for the inventory to have a reference to the player
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
Is there a monobehaviour function that recognizes focus in the hierachy?
what are you trying to accomplish
I'll try asking in editor-extensions
its more of an editor I guess
are you trying to make an object that nobody can modify in editor or something that wont' be affected by physics or game logic
correct
that was an or question
cant be modified
make it static
make it static?
you can also make it unselectable
yeah, I'll try that one
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
Ive never had a use for this but https://docs.unity3d.com/ScriptReference/HideFlags.HideInHierarchy.html
There is also this
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
I have had a use of the show not serialized field from here https://github.com/dbrizov/NaughtyAttributes
Maybe this is more of what the guy wants
Yeah, so I can still see and drag the transform arrows when I lock the hand in hierarchy
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
keep in mind once you add that script it's uneditable
including being able to remove scripts from it
so have fun with that 
you'll have to edit this script in order to gain control back
There is just a single script on it
😆 - perfect
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
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
I should pay you to help me out. Things would go a lot faster.
This struggle is good for me. No pain no gain.
it's not a terrible idea. sounds like you have a moron designer. and i'm all for disabling moronic designers
Yeah, I am the designer 😆
oh 
You are not far off.
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
ha - guy was doing what designers do best
fr
artists and designers should be kept away near any deadlines
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
he holds the infinity stones. Smart guy.
Sure way to get fired
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
is it an actual tool or more like a glorified script?
when asked why he didn't commit them, he said he still hasn't figured out sourcetree. we just shipped a few months ago
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).
@cold parrot it's a scene with a suite of editor scripts
I mean, is it robust, so that it isn’t dangerous to use?
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 
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
I've heard far worse tales than this one bard.
you know NASA spent millions of dollars designing a pen that can write in space? russians brought pencils
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
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
Maybe because it’s a best practice in large companies to eliminate the security/platform/update issues you get with desktop tools… but obviously that’s an overhead that isn’t always relevant especially for small teams
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?

Google brains are the worst 😂
especially since there's like 12k google brains without jobs now
the whole web world rn, in their practices are pretending they are Google/Netflix
That means you have a variable called "Component", but Unity also has a variable called "Component" thats part of the MonoBehaviour class, so its suggesting to either use a different name, or if you intend to override their "Component" for yours (which I dont think you do), then use new so the engine uses yours instead
or put it in a different namespace
ok thanks
making namespaces match your folder structure is super handy
I'm an artist thinking about starting a comp sci degree.
Would likely take me a decade.
soooooo how do you do that
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
comp sci i sn't that hard. most difficulty in learning is lack of faith in yourself
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"
because the chance of small fragments breaking off from the pencils and potentially harming or killing the expendable crew was of little concern for russians ;)
I've been dabbling in tech art for years
@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
mk
^ Youd have to encapsulate the class in the namespace though
Oh, didnt know you can do that in 10, C# 9 and 10 seem to have a lot of very nice features
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
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
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
Daam, we come a long way-since
honestly bro can i give you the code so you can see
🥲
Sure
mk
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
Please share what the error says if there is an error
Stage is an array, you're trying to assign an int to it
on the script itself under Line32 switch (stageSelect) { case 0: Stage = 0; break; }
Cannot convert int to LevelSO[]
Someone already told you what's wrong
oh... erm
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?
sorry haha i just that stage to spawn when stageselect = 0 got called. 🤔
i think i do this Stage[0]; but still got error
Stage is an array holding LevelSO scriptable objects
Sorry, didn't see the type
oh. ok i think i should have change that SO
wah ok i think i over-engineer things
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
oh ok i think i understand this abit. thank you so much!! wytea ty too! okok
i will try this
it might also help to explain what you're aiming for here with more context - are we spawning a boss if the current stage is a certain stage? trying to keep a state for what stage we're on? etc
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
yea 😅 really trouble understanding here. okok i will study more of this method.
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)
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
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
What script are you calling Awake and OnEnable from UIDocument?
Hello, I have the hierarchy in the top i'm calling it in WinMenuUIController
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);```
how you usually show a menu in UI Toolkit becasuse documentation is very bad and it has no sense that i cannot disable the document initially if it has not to be used initially
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...
This is because the api you are using https://random-word-api.herokuapp.com/word is not a list of objects is a list of strings
So you have to do that
List<String> randresult = JsonConvert.DeserializeObject<List<String>>(randjson);
Since it's a **value and not a key value **
ok thanks. I tried this but now I can't access my RandomWords variable
randword = randreader[0].
sorry, shoulve given some context lol
public class RandWord
{
public string[] RandomWords { get; set; }
}```
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
yeah but since it starts with two brackets it is seen as an array. if i deserialize it without using List<Root> it gives me an error that it cant deserialize an JSONarray so it has to be in the form of a JSONobject
hopefully that makes sense
Yes but this -> List<RandWord> randresult = JsonConvert.DeserializeObject<List<RandWord>>(randjson);
is this -> ```[{RandomWords: ["hi"]}, {RandomWords: ["hi"]}]````
ahh I got it to work. thanks for the help! yeah I kept thinking i would have to do randresult[0].something_here
thanks :)
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
how are you trying to set the data?
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);```
done
can you show your whole code
i can't tell if you're running a coroutine or not or where you're triggering it
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
when you dequeue, it's not going to call the constructor again as the object already exists
you can use an actual object pool
simplest way would be to move all initialisation into an Initialisation method, call that from the constructor, and also call it after being dequeued
object pools have callbacks for construction and retrieval
hmm can u point me in the right direction
is that the proper one with the whole <T> business
or what Stropheum is suggesting, it would be nice if that sort of thing is handled in the pool system itself
just to clarify, there is no way to call the constructor again as the object already exists?
nothing straightforward i mean
you can override it with a new allocation
defeats the purpose of preallocating them
Maybe move the contents of the constructor into a method and call that with both the constructor and whatever that needs the calling of the constructor thereafter.
so a true object pool system would solve this?
yes, because you can use ontakefrompool to configure the already allocated chunk
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
How can I reduce wobbling on a configurable joint being used as a spring?
you don't need that complexity in a one-off case
I want the main object to move smoothly towards the other instead of flying around the joint
show
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
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
Google a tutorial and return after getting some working system that's got issues or concerns.
i take it its just a limitation for the reasons you guys said
its bypassing the constructor right
you can fiddle with the settings a bit - spring force will make the spring more responsive and less ragdoll, damping will reduce wild changes, increase both and you'll end up with something more like a pneumatic robot arm
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;
}```
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
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)
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?
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
aah i see thank you, anyway is there any downside to doing this? like crash? or freeze when playing on mobile?
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
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?
you gotta understand what async actually means i think
ok, anyway thank you for your information have a great day...
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
oooh wow still had much more to learn... Thank you so much.

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
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
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
Are you talking about overloading operators?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading
yes thank you, dont know why i couldnt find that
Np, its not a unity-specific thing since a lot of languages allow doing that
btw you never create instances of class A for a1 and a2 so you're going to get null ref exceptions
ok good point xD
you cannot do this
UIManager UIM = new UIManager();
on a Monobehaviour class
Or reference the proper way instead of static etc unless it's meant to be s Singleton.
no, a Monobehaviour is a component, so add it in the gameobjects inspector then use GetComponent to reference it
Use instantiate then
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
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
this is programming, literally anything is possible. And yes, it would make sense to do so
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
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?
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?
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);
}```
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
it's the one using the animator, isn't it
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...
you should just be clear on what the class inherits from if it's not monobehaviour
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;
}
}
}
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");
}```
normally you would add a MenuItem attribute
I want to handle it through my editor
[CreateAssetMenu(fileName = "New Head Cosmetic", menuName = "[Cosmetic System]/Head")]
For my scriptable object i put something like this right before the class declaration
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
This triggers error: KeyNotFoundException the given key was not present in the dictionary. Any ideas why this is?
if (hitMaterial != null || bulletImpactDictionary.ContainsKey(hitMaterial))
this code will not generate that error
Thanks, but this is not the way I would like to do this.
|| makes little sense there. You probably wanted && instead.
ya really though containsKey should handle null cases
that's what TryGetValue is for though?
no, dictionary cannot have a null key value
it should generate an invalid key exception rather than a not present exception
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
What line causes the exception?
Maybe BulletImpactManager.Instance is null
Or the dictionary
that would be null ref not a Not present
Oh right, I didnt read above, just assumed NRE
this
bulletImpactDictionary[hitMaterial]
this the only thing that should generate a not present
but with the if that should not happen
I just restarted it and am not seeing it triggered anymore
Not sure what condition is causing it
I think it was the difference between || and &&
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
Where do you assign velocityForTesting?
Can you edit Unity Events via code or just the inspector?
wdym by editing them
you can assign them in inspector sure
Like add/subtract methods in the code like an action or something
I'm using a unity event because I have a class that needs to use different methods from a main script, but after that event is done I don't want it to run again so I have to remove it
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
in the editor you can use this
https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.html
Ooooh, are the listeners the methods in the event that are called?
any clue what's missing when compute shaders wont trigger the intellisense?
tried deleting the .sln
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?
dont think so, only 1 static can exist, 2 players mean u'll end up having 2 player scripts
if there are 6 Player Components on the scene, that static instance will still be only 1, right?
sorry for the beginner question
you're at the beginning of a long journey
you probably want to start with a tutorial or asset
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
hah
alright thank you
It's just the current velocity of the rigidbody2D
How can I destroy a scriptableobject from my editor?
You probably shouldn't? Scriptable Object are almost treated like a singleton monobehaviour objects. Just assign a different value or recycle that existing object for next usage.
Found it. "AssetDatabase.DeleteAsset()"
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?
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
Object.Destroy can destroy a scriptable object for you. Note that if it's a saved asset you'll need to use Object.DestroyImmediate(<object>, true). I recommend being careful with that though
For the second case DeleteAsset also works fine 👍
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.
The raycaster specifically targets Graphic instances, so it has to be at least that
hmm is there another way to do it?
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
How do you display the general zone/area for them to drip the cards? I imagine it's a graphic, no? It can be an image with a low-transparent color. You don't need a fancy graphic . . .
Anybody using Unity Netcode? How can I show worldspace UI only to players that triggers it?
But if you just want to get the screen position when the player clicks, you can check for input and grab the mouse position since it's already in screen space . . .
not a biggie, but anyone know: Quaternion.FromToRotation do I have to normalize the vectors I pass to this, like in the example? (https://docs.unity3d.com/ScriptReference/Quaternion.FromToRotation.html)
There is an underlying graphic. There are basically multiple areas the cards get sorted into after they're dropped, but I wanted to draw one big continuous zone where you could drop the card since they're all abutting each other.
" 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.
I'm learning that presently. What I do is essentially I have a player_ui that isn't a networked object and isn't synchronized, and any UI stuff for the player gets spawned there and then situated to world space, but not a child of the synchronized environment.
like im imagining a pop-up menu on an interactable object or something?
Yeah. I have a chest and want pop up text on top of it. But can't really figure out how to have that text as a child of the chest and not make it network object
Don't make it a child of the chest. You can create an anchor that always references the chest position, but keep the pop-up out of synchronized objects.
Oh that makes sense. Thanks
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...
if anyone cares, tests say: yes
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
They're all affordable. Rigid body has got more things going on and regular update can occur less often than fixed update.
I realized rigibody being a lot better since I'm gonna make a moving platform on a multiplayer game
yeah definitely, thanks
what s the intellisense?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio: https://on.unity.com/vshubconfig (Installed via Unity Hub)
• Visual Studio: https://on.unity.com/vsmanually (Installed manually)
@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
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
OnValidate . . .
Okay. so apparenly all I had to do was if(isOwner) 😄
Thanks, but what if your not using monobehavior?
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 . . .
what is it then?
No memes/gifs.
Idk, that is why im asking lol
sorry
yes! I was making an "always face camera" script. I tried NOT normalizing the camera-object offset.. result did FACE camera, but it "spun" the object around as I changed distance (changed "up")
No idea why dyno was so slow to get that one lol, I thought it was manually posted because it didn't get it
if its a scriptable object it has on validate as well, thats why i was wondering
Then what are you using? I know it works for MonoBehaviour and ScriptableObject . . .
o, its just a normal class, with the iseriazationcallbackreciever
That normal class must be an instance on a MonoBehaviour or ScriptableObject, no? 🤔
ScriptableObject is MonoBehaviour Wink wink 😄
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
where is the issue, or rather how do I read that property
so why is it even there
You can see its arguments in your popup, it has out parameters.
do this
int workers = 0;
int completed = 1;
ThreadPool.GetMaxThreads(out workers, out completed);
ou that s how it works
so it s basically the same as passing a refference, and changing the value of the refference to something else?
yea I guess, you might want to look at msdn for differences
one advantage of this is that if the function fails, usually your program doesnt crash since the variables are already initialized
I don t see why that would stop crashing but it seems like really great syntax stuff
That is where you call OnValidate (in the MonoBehaviour) and change/edit your variables . . .
yea...your right, It should just call it in the main function
Your right, normally they are used with alot of tryparse method which I presume was to prevent runtime errors
"out requires that the method accepting the parameter MUST, at some point before returning, assign a value to the variable."
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?
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
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.
Get the dot product and use that to lerp between different clamp values
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
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
I know what dot product is and lerp, but I don't understand what you mean to use them together.
If you want the very simple case of what you drew, something like this could work:
myVector + myVector * clamp(dot(myVector, Vector.up), 0, 1)
This would give you twice your vector when directly going up, and less as you start to deviate from the up vector
Wouldn't this give zero if going backward, so it would just nullify it instead of adding backward?
dot product of (0, -1) and (0, 1) is -1, which gets clamped to zero. whatever myVector is * 0 will be 0.
Hence the myVector + myVector * ...
ok, so this sort of decomposes the vector2 into just the forward part, then only modifies that part.
ok I think this works for me. Thanks.
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 . . .
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.
think people assumed it was normalized from the start
You said your vector was clamped in magnitude, that sounds like it's normalized already . . .
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.
Earlier, they provided a result for front/back. You'll need another solution for left/right if you want it to be different . . .
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.
Why is my public bool isn't referenced in the unity script interface ?
You saved your code right?
Yes
And no compiler errors
No
is there a way to force unity to not save playerprefs on application quit?
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?
i was just curious if i could nevermind
Why would a collision be read between the gun and the bullet here? There is no overlap of colliders?
sorry misread the first time, is that where it gets instantiated?
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
You could always Debug.log the collision.collider to find out
Which one it hits
How are you checking for collision? Just set the initial position of the bullet at a point where it doesn't collide with the gun. You should have a spawnPoint child Transform for the gun . . .
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?
Button has a property called SpriteState on it
you create a new one where its green for pressed and set it on the button
do all of the IEventSystemHandlers (IPointerDownHandler, etc) function the same in the new input system versus legacy input system?
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
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
it also seems like it's easier to manage different game states with it by switching maps
can you save a list of bools to json? or no
json supports bools and lists just fine
alrighty, i need to review my code then haha
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
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
yeah sorry I need the distance to never be less than 2 from any the points in list
tried to foreach through the growing list of random points but compiler yells at me
you can use the Any method from linq to see if any of the objects in the list meet the condition
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
if(randomMidPoints.Any(x => x != currentPos && Vector3Int.Distance(x,currentPos)))
would replace inner foreach loop and condition
awesome!
let me give that a try
also why Debug.Break
Debug.Break just pasues unity
oh right, that also doesn't include the check that the point is already in the list you can use the same Any method just change up the condition a bit or use Contains
take a look at where that error is and see if you can figure out what is wrong with it
i know, and i know exactly what is wrong with it too
Sorry this is like my second time using linq lol
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.
collection was modified enumeration operation may not execute
dang
you removed the foreach, right?
ye
show the current code
.
scratch that! im dumb
i didnt save it
Thank you!
oh its no error but doesn't work @somber nacelle
i assume by "doesn't work" you mean it is still adding duplicates to the list in which case ^
duplicates has not been the issue hashset helped , the issue was not wanting to add a point that is less than 2 distance on any v3 in the list
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
I just switched it and got infinite loop
gotta force close
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
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);
}```
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
so would it be cs if (!randomMidPoints.Any(x => x != currentPos && Vector3Int.Distance(x, currentPos) < 2)) ?
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
I would like the while loop to keep trying
until it is met and filled with let's say 3
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)
is there a better way I can do all this ?
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
my controls somehow got turned into a visual studio's file, how do i change it back to an inputactions file?
I need the list of v3 though because of the tilemap coords
well you could start reducing the minimum distance required every number of iterations so that you can guarantee that spawn points will be added or whatever. you just have to do something that will eventually lead to the loop ending if not enough of the points in that initial collection satisfy the condition or else the loop will never end which is your current issue
don't crosspost
sry
also not a code question anyway
anyone run into problems with animations and nav meshes? for some reason this sucker refuses to just REACH their destination and they start moonwalking in circles when they get where they're supposed to be
https://streamable.com/llw4qq
https://paste.myst.rs/akyhknrb
how could i get it so when you shoot a tank it moves the tank back a bit
is your tank using a non kinematic rigidbody
yes
then simply add a force
would adding a force just be attaching a empty game object to the cannon then passing it in as the vector 3
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?
😫 fuckin lists and linq ... whyy so painfull..
its meant to be a tool to help, if you find it harder to understand linq just use loops
I did try that but it gave me an error that wasn't able to iterate through a collection that grows :\
well its weird being in a case looping while adding to the thing you are looping
unless you are doing a while loop
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
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
My only guess is that input changed between the two platform.. where destination on the second might have been an unwanted Vector3.
would adding some logging, see if what you are passing to add force differs alot between them
:\
how should i calculate the direction to knock the player back, im thinking this.transform.position - endOfBarrel.transform.position
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
get rid of the first part of the condition inside the Any call
do you mean x != currentPos
yes
what do I put instead to not get duplicates
I think....that...worked..
holy mushrooms!
@somber nacelle thanks alot! you saved me days of heartache fr
ty
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
Coming back to this - so the problem must be in my code. There's no differences between how an IENumerator works in Android vs Windows?
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
yeah I was afraid that was the case, all good, thanks for helping clear that out
i'll make do with these
is there a way to amplify addforce
wdym by "amplify"?
multiply your vector by a bigger number
ight
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
im using impulse but its still too little
then yeah, use a bigger amount of force
or you are overriding it by assigning velocity every frame
multiplying it did the trick
do you use velocity for movement?
or do you actually use AddForce for regular movement?
addforce for regular movement
there is a whole discord for it pinned in #archived-networking
how would i rotate the tank cannon bone to the direction the player double taps (for a dash)
