#archived-code-general
1 messages · Page 360 of 1
ohhh yeah
makes sense
Does that really need to be explained? Because it is awful, nausea inducing, blurry, doesn't show everything, and against server rules.
@static matrix also using lambdas generates garbage.
hey can anyone help me?,
i made a death popup thing and instead of only popping up when the player dies, it does it right after i click play/run
Are you going to post some !code or do we just have to guess at what you have done?
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So you just totally ignored the bot message
whats backquotes
oh
using UnityEngine.SceneManagement;
public class GameOverManager : MonoBehaviour
{
public void RestartGame()
{
Time.timeScale = 1f; // Unfreeze the game
SceneManager.LoadScene(SceneManager.GetActiveScene().name); // Reload the current scene
}
public void QuitToMainMenu()
{
Time.timeScale = 1f; // Unfreeze the game
SceneManager.LoadScene("Main Menu"); // Load the main menu scene (replace with your actual main menu scene name)
}
}
i cant send the other script
too big
to be extra fancy, add cs after the first three backticks
use pastebin, then
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Debug your code, specifically the TakeDamage method
is the problem that i start with 0 health or something?
i did set the currentHealth to MaxHealth
obviously
public int currentHealth;```
irrelevant, look at the values in the inspector
wat
What is maxHealth set to in the inspector
wdym on the inspector
omg
The window named "inspector"
ik about the window
So look at it
and see what maxHealth is set to
on the script component
me when someone insults my entire lineage vs me when someone tells me to go to #💻┃code-beginner
im just joking
but it can feel like a gut punch when you think you are good at coding 😔
Don't fret it, for some even #💻┃code-beginner is too advanced, unfortunately we dont have a #code-notabloodyclue
#code-preschool
#blockcode
So i came across the IEnumerator and i wonder what it is? i think its a return type thats executes your code but u cant tell it to wait a few seconds until he executed your code again? right?
It’s an an operation that you can step through from the outside.
Unity can automatically do that for you ‚one step per frame‘ —> Coroutine
why if i got angel sheep in my Items list in inventory name rarity and itemicon are not right but spawns right sheep. if i restart game item name, icon, rarity are right
i tested now it happens with every sheep skin not only angel sheep
I assume this has something to do with it:
why assume? Check. But yes, that looks like very silly code to have in the Update loop
how should i fix it
is there a reason you LoadPlayerData every frame ?
i change items list in game manager
which is even more reason not to load EVERY FRAME
if i load it on start inventory doesent update
I think the core problem is that you have the items on both the GameManager and the InventoryManager.
Also, from where do you call ListItems()? I get a feeling it's from an Update() method in another unrelated class.
List items is called with inventory Button
ok, what it happening is:
You add a sheep ->
ListItems() is getting called ->
You loop through all the items, starting with the first item (normal sheep) ->
The if statement gets triggered because Items.Count is now increased by 1 ->
You create a new sheep display ->
You take the data from the first item, which is a normal sheep
You should also have your item display be it's own class, something like this:
public class ItemDisplay : MonoBehaviour
{
[SerializeField] private TMP_Text itemName;
[SerializeField] private TMP_Text rarityText;
[SerializeField] private Image icon;
[SerializeField] private Color rareColor;
// ...
public void DisplayItem(Item item)
{
itemName = item.itemName;
// ...
}
}
------------ In your InventoryManager -----
public ItemDisplay InventoryItem; // replaced 'GameObject' with 'ItemDisplay'
public void ListItems()
{
// ...
ItemDisplay display = Instantiate(InventoryItem, ItemContent);
display.DisplayItem(item);
}```
Basic question: I have a box collider 2d on my enemy as the main collider. I also have a circle collider 2d set to isTrigger to act as a sensor to know what objects are close. On the enemy i have it set to the enemies layer which i mask for on my players raycast to determine if I hit an enemy. The issue I am having is that the circle collider is registering as hit which is unintended. I tried setting the Layer Overrides to ignore raycast (and everything) but that doesn't seem to function like i thought it would and is still captured by the raycast.
put the circle collider on a child gameObject and change the Layer
That was what I thought of as a solution, just didn't want to have to rebuild my prefabs (im lazy) but does seem to be the smart way to handle it
Thanks
Was hoping I was misunderstanding the layer overrides field and they would solve my issue
and just checked the docs (which i should of done first my b) where it clearly states layer overrides are between colliders not raycast and collider.
im using object pool but i cant select an object based on percentage from object pool, should i create more than one object pool for this??
Layer overrides have to do with actual collisions. They don't affect Raycasts at all
Which you seem to have realized
Select an object based on percentage? Can you elaborate?
i realize im not clear enough, sorry for my bad english let me to use gpt
An object pool is kind of meant to just return an unused object (or in some cases, reuse the oldest object), it usually doesnt perform any logic like percentage selection, that logic is usually done after retrieving the object from the pool - but it does depend on exactly what you might be trying to accomplish
I am adding coins with different values to an object pool, but the more valuable coins should appear less frequently. When I use the pool.Get() method, it's not working as I want it to
yes but idk what i can use for this it should be optimized too
after calling the coins from the object pool, i was thinking of assigning new scriptable objects to them but they also have different colors or meshes
should i use dictionary
what is the best UI i can use for preserving presents and put icons that represents each present on them? (plz don't tell me to put bunch of buttons xD)
like a vertcial bar that contain presents name or icons (i don't mind)
Probably something else, yeah... It sounds like you want to randomly draw an item from a collection, where each item type has a different probability of being chosen. That's not something which an object pool is really meant to do or handle.
You might try researching "weighted collections" or "loot tables"
thanks
you're gonna need to provide more info than that, but on a hunch, you have to actually update your position. tform.position.x = xvalue
also #💻┃code-beginner
thanks
Where can I find people who want to team up with me to make games.
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Im not sure I fully understand what you mean, but if you dont need these UI elements to be clickable, then you dont really need a button, they could just be images (or texts), if its a lot of elements you could generate them by code and either use a layout group or calculate their positions based on the rect size and some "padding"
Asking for labor in general (even when there is pay) is difficult, even for the AAA industry, though maybe thats a conversation for a different channel
I just want to work with someone on games for fun, a hobby, someone who shares a interest in making games.
If you have no preference for the project you work on, maybe you could try game jams or collabs, the whole point of those types of projects is just for fun and experience, with no real intention to release or generate revenue of any kind
So I've been working for a bit on a concept game using the visual scripting, not looking for help with that i'm at a point where i need to restart, so i'm reevaluating if it's worth using it or not
it seems like certain things are pretty convienient, but it also seems like other things are very difficult to do when they would be simple in code.
I noticed most Unity examples i've seen using a lot of regular scripting instead, do y'all have opinions on that?
Right off the bat performance is a huge one
well this channel is specifically a code channel, so the prevailing preference here would be "code"
I can have an ide with 25,000 lines of code open without a hitch
Even a fairly basic script graph uses a load of performance in the editor
thats fair, but eheh my experience with the visual scripting discord seems to be that it's somewhat inactive...
Visual scripting is slightly easier for extreeemely basic things. About the same for slightly more complex things, and waaaaaaay harder for anything worthwhile
What's the main drawbacks, the event management?
That has not been my experience. If you ask there, people will generally answer
Maybe not the same day
Having to move around premade boxes, and needing to code your own boxes for anything not provided (which means you need code anyway)
the biggest drawback of using visual scripting is that everything looks like a big old mess of spaghetti. also to get any help with it you have to use the #763499475641172029 discord which, as you've pointed out, is not as active as this one
All of these are pretty good points, yeah.
another drawback of visual scripting is that you aren't learning any real world skills... like nobodies going to hire you for that
i do like being able to see what nodes are active live while testing, but yeah i can probably more or less do that in the debugger with regular script
I just mainly find it's really really performance heavy
At least in the editor, I got no clue about runtime
I can't imagine the headache that comes with trying to optimize visual scripting on the user-developer end.
at least from when i was testing a very very simple project, it was much faster when not viewing the editor
but idk how it would compare to regular script
i kindof imagine it must be compiled to regular script eventually...
Yea I think I've read it's not compiled to something manageable by a human though
For VSG/Bolt at least
Actually does it have its own method for saving and loading or are you still making a serializer anyway
I'm not sure if this should go to animation or here, but since it's mostly code I'll just post it here
So, I want to enable an animator, sample the animated positions, and disable the animator afterward.
animator.enabled = true;
animator.Play("Die");
animator.SetBool("Die", true);
for(int i = 0;i < bodyParts.Count;i++)
{
bodyPartEndRotations.Add(bodyParts[i].rotation);
bodyPartEndPositions.Add(bodyParts[i].position);
}
animator.enabled = false;
but it always returns default pose (not the T or A pose, but the pose when not in playing mode)
The code above is inside LateUpdate function. Is there something I missed?
Or maybe the animation transform only available on the nextframe after it's enabled?
if im in prefab mode what is the general approach to stop OnEnable registering my object to my manager?
i need it to work in scene and in run time but not when im in the prefab editor
I’ve never used it this way but there is https://docs.unity3d.com/ScriptReference/SceneManagement.PrefabStageUtility.GetCurrentPrefabStage.html
Drew up a diagram for something I am wanting to achieve, I was wondering what the most efficient route to make this possible for a 2D platformer so that I can eliminate the need for load screens and make exploring seamless. If anyone more experienced with 2D games could give me some pointers that would be appreciated!
More specifically, I want it to be kind of like a "Layer" where the level you were just on fades out going twoard the screen as you enter the new room area
My question is that when I put down items into a backpack, then pickup the backpack out of its slot (triggering the save function in StorageData.cs), and then put the backpack into its slot again (triggering the load function in StorageData.cs), why does it load the items but I can't pick them up, when I usually can pick them up without involving backpacks. I will tell you that I think it has to do something with the inventoryItemSlot array. But I need help badly please.
Load the new scene additively /asynchronously when the player gets near the doorway.
If they enter, you can activate the scene. You can also unload it if/when they step far away from the door and don't enter it
For starters share the !code correctly:
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
And then also share whatever debugging steps you've taken so far.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I've debug logged that:
public InventoryItem PickUpItem(int x, int y)
{
Debug.Log("x: " + x + "," + "y: " + y);
Debug.Log("2nd: " + inventoryItemSlot[x, y]);
InventoryItem toReturn = inventoryItemSlot[x, y];
if (toReturn == null) return null;
CleanGridReference(toReturn);
if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);
return toReturn;
}``` the debug logs are not both validly logging, only the first one :/ so toReturn always logs null
even though I am setting it in StorageData.cs
Meaning that the InventoryItemSlot element that you're trying to access contains null. So you just need to debug whenever the array is modified.
To see when it's being set to null and why.
ive logged everything and its not adding up but I will go thru one more time
I mean this is logging correctly here,
public void LoadGrid(ItemGrid grid)
{
string path = Path.Combine(Application.persistentDataPath, "gridState.json");
if (!File.Exists(path)) return;
string json = File.ReadAllText(path);
if (string.IsNullOrEmpty(json)) return;
GridState state = JsonUtility.FromJson<GridState>(json);
grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];
Debug.Log(grid.inventoryItemSlot);
foreach (ItemState itemState in state.items)
{
if (state.items.Count == 0) return;
InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
inventoryItem.Set(itemState.itemData);
RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();
Vector2 newPosition = new Vector2(
itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
-(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
);
rectTransform.anchoredPosition = newPosition;
inventoryItem.onGridPositionX = itemState.posX;
inventoryItem.onGridPositionY = itemState.posY;
rectTransform.sizeDelta /= rootCanvas.scaleFactor;
}
}```
I don't see you assigning anything to the array in this code.
grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];```
This creates a new array. It doesn't assign anything to it.
how?, it literally states grid.gridSizeWidth and heighth
oh you're saying I need to do like:
in the foreach, grid.inventoryItemSlot[x,y] = the inventoryItem
or in a for loop or whatever
These are the dimensions of the array
I need to actually populate it with items from the state save
is that what you're saying? ^
Yes. That would be an assignment to an element of the array.
Okay I compeltely just dodged that lol thanks let me try that
public void LoadGrid(ItemGrid grid)
{
string path = Path.Combine(Application.persistentDataPath, "gridState.json");
if (!File.Exists(path)) return;
string json = File.ReadAllText(path);
if (string.IsNullOrEmpty(json)) return;
GridState state = JsonUtility.FromJson<GridState>(json);
grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];
foreach (ItemState itemState in state.items)
{
if (state.items.Count == 0) return;
InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
inventoryItem.Set(itemState.itemData);
RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();
Vector2 newPosition = new Vector2(
itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
-(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
);
rectTransform.anchoredPosition = newPosition;
inventoryItem.onGridPositionX = itemState.posX;
inventoryItem.onGridPositionY = itemState.posY;
rectTransform.sizeDelta /= rootCanvas.scaleFactor;
grid.inventoryItemSlot[itemState.posX, itemState.posY] = inventoryItem;
}
}``` how ain't this workin?
You'll need to define "not working"
I am quite literally populating the array? but its not carrying over to this line (where it says 2nd:
public InventoryItem PickUpItem(int x, int y)
{
Debug.Log("x: " + x + "," + "y: " + y);
Debug.Log("2nd: " + inventoryItemSlot[x, y]);
InventoryItem toReturn = inventoryItemSlot[x, y];
if (toReturn == null) return null;
CleanGridReference(toReturn);
if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);
return toReturn;
}```
sry i was typing that
Then nothing is assigned to that array at that index.
Debug what is getting assigned at what index.
This just debugs the indices. Not what is assigned.
nah but what I just send above is logging the firsat one and then the Debug.Log("x: " + x + "," + "y: " + y); in PickUpItem() is logging the 2nd one. They are literally the same. So if it is checking where it was assigned earlier, why is it checking it null?
That's why I'm telling you to check what is assigned.
alr i will
These logs tell you literally nothing aside from the fact that these indices are used somewhere.
(From StorageData.cs) Debug.Log(inventoryItem); this logged an InventoryItem.
what? Debug.Log(itemState.posX + ", " + itemState.posY);
Debug.Log(inventoryItem);
thats just this but in one msg?
This is not ideal, but would do. Make sure to not collapse the messages in the console.
yeah I already logged those tho
Where's the second log then?
the first one logged an identical position to that in the PickUpItem(), and the 2nd is logging the name of the newly loaded item.
Ok, and what does it log when trying to access the item at that position?
Share the updated code.
public InventoryItem PickUpItem(int x, int y)
{
Debug.Log("x: " + x + "," + "y: " + y);
Debug.Log("2nd: " + inventoryItemSlot[x, y]);
InventoryItem toReturn = inventoryItemSlot[x, y];
if (toReturn == null) return null;
CleanGridReference(toReturn);
if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);
return toReturn;
}```
```cs
public void LoadGrid(ItemGrid grid)
{
string path = Path.Combine(Application.persistentDataPath, "gridState.json");
if (!File.Exists(path)) return;
string json = File.ReadAllText(path);
if (string.IsNullOrEmpty(json)) return;
GridState state = JsonUtility.FromJson<GridState>(json);
grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];
foreach (ItemState itemState in state.items)
{
if (state.items.Count == 0) return;
InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
inventoryItem.Set(itemState.itemData);
RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();
Vector2 newPosition = new Vector2(
itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
-(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
);
rectTransform.anchoredPosition = newPosition;
inventoryItem.onGridPositionX = itemState.posX;
inventoryItem.onGridPositionY = itemState.posY;
rectTransform.sizeDelta /= rootCanvas.scaleFactor;
grid.inventoryItemSlot[itemState.posX, itemState.posY] = inventoryItem;
Debug.Log(itemState.posX + ", " + itemState.posY);
Debug.Log(inventoryItem);
}
}```
the log with "2nd" in it is logging nothing
Ok, so there are only 2 possible explanations:
- the load script references a different
gridobject. - you modify the array somewhere else between load and before the pick up calls.
hmm I will log the grid names
and give the new grid a random number for a name on its creation
Pass the object as the second parameter to debug.log. Then you can click the message to highlight the object in the editor.
alrighty
public InventoryItem PickUpItem(int x, int y)
{
Debug.Log("x: " + x + "," + "y: " + y);
Debug.Log("2nd: " + inventoryItemSlot[x, y]);
Debug.Log(transform.name);
InventoryItem toReturn = inventoryItemSlot[x, y];
if (toReturn == null) return null;
CleanGridReference(toReturn);
if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);
return toReturn;
}```
```cs
public void LoadGrid(ItemGrid grid)
{
string path = Path.Combine(Application.persistentDataPath, "gridState.json");
if (!File.Exists(path)) return;
string json = File.ReadAllText(path);
if (string.IsNullOrEmpty(json)) return;
GridState state = JsonUtility.FromJson<GridState>(json);
grid.inventoryItemSlot = new InventoryItem[grid.gridSizeWidth, grid.gridSizeHeight];
foreach (ItemState itemState in state.items)
{
if (state.items.Count == 0) return;
InventoryItem inventoryItem = Instantiate(inventoryItemPrefab, grid.transform).GetComponent<InventoryItem>();
inventoryItem.Set(itemState.itemData);
RectTransform rectTransform = inventoryItem.GetComponent<RectTransform>();
Vector2 newPosition = new Vector2(
itemState.posX * ItemGrid.tileSizeWidth + ItemGrid.tileSizeWidth * inventoryItem.WIDTH / 2,
-(itemState.posY * ItemGrid.tileSizeHeight + ItemGrid.tileSizeHeight * inventoryItem.HEIGHT / 2)
);
rectTransform.anchoredPosition = newPosition;
inventoryItem.onGridPositionX = itemState.posX;
inventoryItem.onGridPositionY = itemState.posY;
rectTransform.sizeDelta /= rootCanvas.scaleFactor;
grid.inventoryItemSlot[itemState.posX, itemState.posY] = inventoryItem;
Debug.Log(itemState.posX + ", " + itemState.posY + grid.name);
}
}``` like this?
Debug.Log(text, objectReference);
@cosmic rain .......
public InventoryItem PickUpItem(int x, int y)
{
Debug.Log("x: " + x + "," + "y: " + y);
Debug.Log("2nd: " + inventoryItemSlot[x, y]);
Debug.Log(transform.name);
InventoryItem toReturn = inventoryItemSlot[x, y];
if (toReturn == null) return null;
CleanGridReference(toReturn);
if (toReturn.itemData.itemType == ItemData.ItemType.Backpack) RemoveGrid(toReturn);
return toReturn;
}``` the third log, umm, logged a different name than the one in the Load method lol
Well, then it's a different object
I bet that it references the prefab, instead of the object in the scene.
where
Wherever you reference it. Probably in the inspector..?
Wherever you're passing it to the load method.
nope,
ItemGrid gridAdded = AddGrid(inventoryItem);
inventoryItem.GetComponent<StorageData>().LoadGrid(gridAdded);
return true;```
Then AddGrid returns the wrong object.🤷♂️
from AddGrid:
GameObject newGrid = Instantiate(itemGridPrefab, GameObject.Find("StorageGrids").transform);```
and ```cs
return newGrid.GetComponent<ItemGrid>();```
I mean, just look at your hierarchy. You should be able to find the two objects just by looking.
it doesn't because this:
GameObject newGrid = Instantiate(itemGridPrefab, GameObject.Find("StorageGrids").transform);
newGrid.name = Random.Range(0, 1000).ToString();``` turned out to be 85, and logged as a name of 85 in the load method
And what name was printed in the pick up method?
the slot where the backpack is in
which was just "Backpack"
yes
I feel like I really don't understand your setup anymore.
here
Which one do you want to pick the item from then?
when I click the Ak-47 it calls pickupitem from the the backpack grid (#1) instead of tthe grid the ak is in (#2)
i just realized that
Great. Then I guess the issue is solved.
i mean ig but how that is happening i have no clue, i will dig thanks for the help
Debug.
The method is called on that object, so just see where you're calling it from and what it references.
alr
Debug.Log(selectedItemGrid);
selectedItem = selectedItemGrid.PickUpItem(tileGridPosition.x, tileGridPosition.y);``` this is where its being called
however selectedItemGrid is logging as the one I ACTUALLY clicked on
Well, where are you setting it?
selectedItemGrid?
well thats correct so idk why that matters tho?
yeah its so weird, its literally logging 88 as the grid name for the selectedItemGrid WHEN I click on then itemGrid with the name 88, but then proceeds to call it from the other script.
Make sure you back up your assumptions with proper debugging.
Well I don't have one being called from the Load method
yeah I did
What other script..?
I mean the other instance of the same script on the grid where the backpack is beign held instead of the items in the backpack
Well, one of them doesn't have the correct reference at the correct timing, so all you need to do is just figure out which one has the wrong reference and where it is assigned.
alr
ay im going to bed gang, thank you a lot though
velocityY is not 0 , its showing very abnormal value
also i am randomly flying in air, any idea what might be happening
can anyone help me here?
Going a bit nuts on this because I'm clearly missing something very obvious. Null ref on the foreach (not within it), but the collection is not null (and reports the correct count in the prior debug) ``` public EntityInstanceManager(Func<List<EntityInstance>> getInstancesFunc, Func<NativeEntityInstance> getNativeFunc, Ship ship)
{
GetInstancesFunc = getInstancesFunc;
GetNativeFunc = getNativeFunc;
Ship = ship;
var entities = getInstancesFunc() ?? new List<EntityInstance>();
Debug.Log(entities.Count); // correctly reports positive number
foreach (var entity in entities) // throws NullReferenceException
entity.Manager = this;
}```
EDIT: Fixed. IDE linecount was off for whatever reason, go figure.
This is the code channel, you might want to ask this in #💻┃unity-talk
okay ty
Im not sure when, but at some point for some reason, for-loops specifically always report incorrect errors, ive had errors that suggest a line thats literally the } bracket of a for-loop, as if Unitys internal debugger just cant figure out what line of a for-loop is relevant so just marks the whole for-loop as "problem is here somewhere... I think" - good to hear you got it sorted but at least you know if it get another error specific to a for-loop, it might be a misleading debug from Unity itself (at least, AFAIK)
I got a few like these but with IndexOutOfRangeException, they would always report at the end of the block even if the array indexing (that was faulty) was 10 lines above that
And it is the compiler Unity uses, since it doesn't happen in regular .NET apps
This is a code channel delete and repost in #🛠️┃probuilder
thanks!
How to make custom sliders
do not cross post
Idk how to create a custom slider
German ?
What do you mean by "custom"? What would you like to customize about it? And what does it have to do with code? #📲┃ui-ux , no?
Hiii, really new here is there any code the limits the rotation degrees to a certain point, ex this object can only rotate 90°. Thank you
when we talk about limiting the range of rotation we need the axis on which the rotation should be limited on + the range of angles it should be able to move in
so how would you like the rotation of your object to be limited? do you have any visualisation for it?
Hi slr been eating, but the visuals is this, I don't want the arms of my player to get inside the main, body I did try to put in some coliders but it's didn't work, so I kinda want to limit the rotation indicated by the black line, and thanks
With another texturen and another form
Form?
You can easily change the images as you please. What else are you wanting to do?
Hey it's my first time mapping a controller input for a game, should you use a virtual mouse to control the look action or should you use Cursor warping?
Frankly it's almost always easier to just use a separate action for joystick vs mouse controls as they're too dissimilar to use the same code path
Interesting, Unity automatically shoves them into the same action so I assumed you could just map it to the same thing
I quite honestly don't know much about remapping inputs or using anything other than Keyboard and mouse so I was wondering if anyone had resources on the matter
Sorry what I mean is that I am looking to set up a controller for my game and I am wondering how to map the right stick to the mouse cursor
So how should I go about it
Did you read this?
Yes, I created a new action that is exclusively mapped to the controller
But I want it to be able to control the cursor
First you said it was for a Look action though
What's the intended goal here
Do you actually want it to control a cursor, or just to make the character look around?
Sorry I think there's a lack of clarity on what I am trying to do, in the game the the player has to use the mouse cursor to fire and pickup objects but I also want to offer the opportunity to use a controller if the player wants, I am trying to map the right stick to that same type of function
and I'm not sure how to go about it
Hey, what is the best way to make FPS animation in Unity (Arms or full body animation) and the best way to learn it? Any tutorials?
any1 know how to do faux movement on rotating spheres? I've been struggling for a long time trying to make the movement work both with physics and without, this current example is fully with physics
most of games use Both , Different hands animation for each weapon separated from the body , then they add a fake body with legs , so when you look down you can see some legs , if you want to start i suggest just doing simple hands
and here is a free package with sample of animations : https://assetstore.unity.com/packages/templates/systems/low-poly-shooter-pack-free-sample-144839
Mind dmming me so when I wake up I can see it
can you explain more where is the problem?
no problem
No problem just learning
when trying to move forwards for example, it moves weirdly, i can send you a video
please do
Yea sure I will be happy
If I get any problem in the future can I personally ask u guys?
basically when running the game, the sound sounds quite normal, but when building it, its messed up
yea sure , happy to help
please make sure OBS is recording mp4 not mkv , so we can see the video
alr
one secon d
basically when running the game, the sound sounds quite normal, but when building it, its messed up
during the entirety of this video i was holding W (PS: this works fine when the planet isn't spinning)
Hi guys, just wondering, if you guys got any idea about this, the bullet is kinda off, or not accurate, the picture is my bullet point, where the bullet spawns and this is my code,
https://pastebin.com/Fb0cZz7E
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you can see it slighly shifts the movement, and also completely stops at one point
it's really annoying and I have no idea how to fix it
can you send movement code
can you please just download any mp3 file from internet and make a new gameoject and add to it audio source and test again
your shooting points are rotated a bit , try making a new empty gameoject and place under it the shooting points and make sure there is no rotation
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
what do you mean by that?
this is movement code
mp3*
my shooting points is this, i kinda rotate it to 90 so it would not shoot up
Looks to me like it's shooting accurately, but not taking into account the height of the guns. That is, your mouse hits a point at ground level and the player rotates to face that point at ground level, but the projectiles travel on a higher plane parallel to the ground plane.
Maybe this script could acquire the height of the guns from _player and just set the plane to that height?
(I might be misinterpreting the issue)
alright
okay so simply this is happing because you are using "_orientation.forward" while rotating the object , so simply its forward keep changing
but orientation is literaly the camera's forward:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
[SerializeField] private Transform _orientation;
[SerializeField] float _sensitivity;
float _xRotation;
float _yRotation;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
_yRotation = -180;
}
void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * _sensitivity;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * _sensitivity;
_yRotation += mouseX;
_xRotation += -mouseY;
_xRotation = Mathf.Clamp(_xRotation, -90, 90);
transform.localRotation = Quaternion.Euler(_xRotation, _yRotation, 0);
_orientation.localRotation = Quaternion.Euler(0, _yRotation, 0);
}
}
try using ** Vector3.forward **
possibly, and it kinda aims also correctly when it's in up and down position
i want you to drag this object outside from its parent and check its rotation
just drag it outside every parent , let it stand alone
@timid brook so in this script you drag the camera in the _orientation field
no, it's a separate game object, that keeps track of only the y rotation of the camera
it's parented to the player
yeah sure wait, results when i change it's rotation to all 0 and let it stand alone
Hello, I'm trying to find an asset (might even be in FEEL already) to debug values into gui for easy debugging
Some sort of queue system for debugging that displays GUI
does anyone have the link to the offical unity server
don't crosspost. and not a code question
ok
thats not what i meant 😅 , i mean when it was only 90 degree , when you drag it out , did the rotation values change
ohh sorry haha, it did not change
when i move it out
because unity work with parent-child system , so parent apply its rotation to child
That's what makes me think that the vertical offset is an issue... Like, if you draw a line upwards from your cursor to the height of the projectiles, I reckon that point of intersection is where it appears to be effectively aiming, rather than directly at your cursor.
For a quick test, you could swap out the Vector3.zero in plane = new Plane(Vector3.up, Vector3.zero); with a vector that has a y component roughly reflective of the guns' height.
If the projectiles not crossing at the cursor is also an issue, I think that's a separate problem to be addressed and what Hussien is getting at 👀
it's parent rotation is all zero
ok let me do this too
@hollow pine wait let me understand , is your issue that the bullets are going out as X shape right?
you want them to move in straight line
Yeah I guess I should have asked for more clarification as well, instead of assuming 😅
wait because i think we both might understood wrong 😂
I want them to cross at my mouse kinda like this
sorry for wording this all poorly haha
i would suggest making a capsule that show where is the mouse projecting on the plane
so you can debug it easier
wait let me research this i'm really new, to game dev really really new hahaha
btw how do you set y as the guns height do you just set it at the global ?
Presumably you already have that data available somewhere, as that's the height at which the projectiles are spawned and travel
So, assuming the player object already has access to that data, I would have CubeScript store a reference to the player script, and retrieve that height from there. That way if you swap out player models or weapons or something down the road, the script would continue to use the correct vertical offset
Ive got a custom script Im using to set the parent size to the largest child height, but for some reason it only updates once I tick the fit to height box a few times, Im making sure to set the whole thing as dirty but still no luck
the height updates properly but the layout group wont properly reposition the element
A website to host temporary code snippets.
heres the code
Ok, will try it out, @vague basalt and @hybrid wagon Thanks guys
i guess you are trying to make Content size fitter componenet ?
pretty much
but with unitys build in stuff it seems i cant get it to work right
heres an example with trying what unity recommended:
are you using vertical layout group?
what's the height on the text components?
the height is correct on the text components
but the position is wrong
or actually wait, the height is wrong on the parent of the text component
which is weird since i have the layout group/contet size fitter
oops nvm, was looking at the wrong field, height is correct
what happens if you change it to:
Child Alignment: Top Left
Control Child Size: Check Height
Child Force Expand: Remove Height
and you also need to add some Top Padding
It's definitely possible with the Unity UI System, I recommend playing around with that rather than trying to come up with your own solution.
also this is an in game issue only, in editor it works fine
presumably because it looks like in editor specifically they have code that runs that manually marks the layout to rebuild every frame
any tips here?
give currentAng a default value
so it wont just stay 0?
needs to be assigned something
if i do this?
that works
0f is better as it's a float
ok
so what actualy is the difference between
float currentAng = 0f;
and
float currentAng = 0;
one is a float and the other isnt
but what happens if i dont use f?
might attempt to cast the number from an int or double to a float? microoptimization but also just best practice to append f to float numbers when assigning them
aah
also
flaot a = 0.1f
is correct
float a = 0.1;
is an error because 0.1 is a double
it is ALWAYS good proctice to use the f suffix when dealing with constant float values
yea, when i use decimals then i use the f but if not then i dont
if not then I don't
Well, if you are not working with decimals, you should not cast to a float, yes
ohk
The f is the exact same as writing
float thing = (float) 0
It is just shorter.
Syntactic sugar
aah
thanks alot. thats what i meant by this
makes so much sense lol
Hi there!
My problem is related with class inheritance.
I have many enemies, each with it's own attack Script (EnemyAttackGun, EnemyAttackShotgun...etc), and they all inherit from the class EnemyAttack
When the enemies die I want to disable their attack scripts so they stop attacking while the animation is played.
But since all enemies share the same EnemyHealth script i'd like to avoid having to go through a list of "ifs" to check if the enemy has one script or another (if(GetComponent<EnemyAttackGun); else if (GetComponent<EnemyAttackShotgun)... etc).
Can I use in any way the parent script to avoid this? (something like GetComponent<EnemyAttack>().enabled=false; which I already tested and doesn't work)
that should work, define 'doesn't work'
if theyre inheriting from the same class then callingn getcomponent on the base should def work
then you were probably doing the GetComponent on the wrong gameobject
It gives null reference
Both Scripts are on the same GameObject
The object has this class as a component (public class EnemyAttackGun : EnemyAttack)
The code line i'm using is this one (GetComponent<EnemyAttack>().enabled = false;)
screenshot the inspector
OK add a Debug.Log before the GetComponent and make sure to include the second parameter to make absolutely sure this is the correct game object
I'm not sure if I understand, should i debug the name of the game object (Debug.Log(this.gameObject.ToString())?
not quite
Debug.Log(name, gameObject);
also why not just declare a
public EnemyAttack enemyAttack;
variable in the EnemyHealth script and set the reference in the inspector
let me try that
referencing the class EnemyAttackGun : EnemyAttack as an EnemyAttack : Monobehaviour doesn't work.
I mean, Unity doesn't let you use it
what, yes it does, it is common practice.
post both scripts to a paste site
I've never done that, recommend me a paste site :p
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also post the EnemyHealth script @wintry jackal
EnemyAttack: https://paste.ofcode.org/3bX8r7M9ZRentYPh236YjfM
EnemyHeatlth: https://paste.ofcode.org/38cDascg826Ej4WQw3iHeBM
EnemyAttackGun: https://paste.ofcode.org/3NL8tThREL5zHeiiJENXUH
ok this is weird, after pasting the EnemyHealth code, the lines im tryng to use rn are missing xd
Like a previous version of the code. Is that normal? O,o
Ok nevermind I was reading smthing else. The lines we want to look at in EnemyHealth are 119-154
void Die()
I think you may have compile errors, is your IDE configured?
131 is the line giving null reference
that is a run time error
Well thats way above my payroll D: (i don't even know how to do that)
Everything works fine but this
and no errors displayed on the console.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
No
also atocompletion and underlining errors etc is working fine
Just gotta do the steps outlined in the guide you were linked to
Then perhaps it is configured.
Do you have any red underlines currently?
no
could it be i've done something wrong with the class inheritance?
I think this is allright btw
if you're receiving runtime errors that means you can enter play mode which means you shouldn't have compile errors because unity will prevent you from entering play mode with compile errors
So I'm looking to position points in a sphere formation. I want these points to be equally distributed across the sphere, and I'd like control over how many points there are.
Any tips? For example, a simple UV sphere isn't good because so many of its vertices are concentrated at the poles.
I'm kind of ashamed but, EnemyAttackGun had not been saved yet
it works
sry for making u lose time :__D
hey, does anyone have experience with object pooling?
classic lmgtfy type link
indeed
if you'd bothered actually asking something instead of asking to ask then you wouldn't have received that link
I feel so dumb, thanks for your care bud, you rock ❤️
anyway, i have a basic pool of GameObjects set up with a max pool size of 30, but when i'm calling pool.Get it's going well over the maximum size
and never calling my return to pool method
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
one more point. your Shoot method wont work. it needs to be marked as protected abstract or virtual in EnemyAttack and override in EnemyAttackGun
Ty so much 🙂
i guess the real question is whether pool.Get is what i should be using here or if there's another built-in method for creating/drawing from the pool
are you using unity's ObjectPool class, your own, some other one from some package/asset? We have no way of knowing and you've not shown code
unity's ObjectPool class
but typically yes, Get is what you would use to get an object from the pool
then yes, you should be using Get to get objects from the pool and Release to release an object back to the pool when you are done with it
instead of just reposting the link, why not bother explaining what is going on ? I have no idea what I'm looking at.
also where is the code question exactly?
anyone have a solution
if i have a maximum pool size set and the pool goes over, it should be calling the method i set for the release action, right?
solution for what? You haven't even asked a question yet
that is a door with a script, with the code attached. I got it from a ytber cos idk anyth abt coding. The door doesnt open like a regular door, it twists upwards asw as shown in the ss, which is the issue
first things , this clearly belongs in #💻┃code-beginner
second. You have to show the CODE and the Pivot points clearly visible
so show the inspector of the door
you're rotating on the Z which is very wrong
and X
you should only rotate Y on a door
so you have uneven scaling which will cause problems when rotating
that too
that was just to get the door in the right position
how can i fix it
first of all make a parent object that is the actual door. Keep the scale on that one on 1,1,1
make the child door(the one with the graphics) position, match the parent on the Hinge part of the door (the corner where doors normally rotate from)
after that rotate the parent object on the Y position
the door doesnt work now, i dont even get the 'click e to open' oiption
is there a way to check how many objects are currently in a pool?
you're just jumping all over the place..
start with fixing the rotation and movement first
done
rotates on hinge
awesome, thanks
yes
alr then. So what is issue now ? show the !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ah, ok. so the max pool size isn't a cap on how many objects can be in a pool
ok so what is happening now vs what you expect ?
it's how many inactive can be in the pool. once that cap is reached further objects released to the pool get destroyed instead
same thing
should i have the door script on the parent or child
its on the child rn
everything besides the graphics belong on the root object (parent)
wdym graphics
collider too
gotcha, inactive objects. what i'm trying to do is have a pool of objects that recycles the oldest object in the pool when it goes over capacity
the mesh of the door
oke
seems like calling pool.Get() is creating new active objects rather than inactive
now ive lost the open door function, im clicking e
do i need to populate my pool with inactive objects at start?
did you put the collider on the root of the door
where is the script that supposed to open door with E
thats the door script
sending inab
not a requirement, as you grab from the pool it creates the objects if the pool doesn't have enough in it already. though i do typically prewarm my object pools
ok show me the root object of the door, inspector
gotcha, makes sense
you still left the collider on the door mesh didnt you
this collider doesnt seem to have the proper sizes / offset
sorry, last question, how do you add inactive objects to a pool?
you just Release them to the pool
yes
look here is my setup
and you removed the collider from child yes ?
oh you're using UseLayers in code
yours is on Default
thats probably not the uselayers is it
Ah yes I see here its the Usable layer
change it and should work
figured it out! what i needed was a list of active objects separate from the pool. turns out it wasn't a pooling question at all 😄
OI NAVARONE
U R SUM GENIUS
THANK YOU BRU
is there a way to add a creaking sound during the animation tho
yeah just put an Audiosource and do PlayOneshot in the coroutine
hmm new issue now
i cant brign the text closer to the camera
so its blocked off
top is game view
seems more of a #🏃┃animation question than code
alright, thanks
is this a world canvas? just bring the canvas closer
"its a text" yes I can see that
Why is the text a world canvas if you dont know what that is..
ytber again
i really should learn this stuff but id like to get a basline done soon
how can i move the canvas
if you dont learn you cannot progress..
just copying tutorial doesnt teach you anything, its mainly to show you how to do something, its up to you to learn this stuff on your own
otherwise you're copy and paste, and that has no effect on experience
https://www.google.com/search?q=world+canvas+vs+canvas+unity
Unlike a Canvas set to Screen Space, a World Space Canvas can be freely positioned and rotated in the Scene. You can put a Canvas on any wall, floor, ceiling, or slanted surface (or hanging freely in the air of course). Just use the normal Translate and Rotate tools in the toolbar.
how can i change
I'm not here to do a step by step tbh
learn how both work, put a little bit of effort
if its a world canvas you need to move it in the world like any other gameobject and it gets hidden by walls, if you use Overlay you will have text on screen then its up to you using WorldToScreen to place it on specific objects
both are mostly design choices with their own pros and cons
figure it out which one works best
Hey so in this image, on the left I have a Cube Mesh while on the right I have a VFX graph system that spawns a single cube particle.
The particle appears to be smaller than the mesh, even though the particle has a scale of 1.
What determines the scale of these particles relative to the rest of the world?
What about the scale of the visual effect object? What mesh is it using/ what rendering settings are you using?
Also #✨┃vfx-and-particles
Is there a way set occlusion cull to everything when a canvas is overlaying the whole screen?
Maybe just render the UI on a different camera and disable the other one when it's visible?
I want to move a 2d gameobject in a perfect circle, how to do it? Without using parent/child (with script)
Tag me please
@turbid seal cos(angle) for the x, sin(angle) for the y, angle is in radians, 0 aims at worldspace right, TAU is full revolution counter clockwise
Oh cmon how I didn't know that
I'm sorry can u give me an example script if u can
@turbid seal No 🙂 If I did, it wouldn't be as much fun
You have the wonderful unity mathematics library at your disposition. The process is simple, for any given angle, cos and sin will return your x and y values for a circle of unit length. If you want a bigger/smaller circle, multiply those values by the desired radius.
Interpolating the angle works the same as interpolating the value of anything else. If you've ever moved something outside of the physics simulation, this is no different.
Remember cos and sin, along with trig functions in general, work with radians, not degrees. If you prefer to work in degrees, you need to convert it to radians before passing it into trig functions.
https://docs.unity3d.com/ScriptReference/Mathf.Sin.html
https://docs.unity3d.com/ScriptReference/Mathf.Cos.html
https://docs.unity3d.com/ScriptReference/Mathf.Deg2Rad.html
Woah man u did all of this for a random guy
Appreciate it
Let's be real, I do it for myself. But no prob
Urself how
Sharing is fun
Ok 😮
Hey guys, so I'm using IPointer handlers for some basic functions in unity. When I run it in the editor its all good and works just fine, but I build an apk for android and suddenly it does not work on mobile, can anyone help me?
I have two projectiles set up so that the only intersect with each other for a single frame and want it so that at least one can see the other for that single frame. One has no collider with this script attached
{
//For the sake of this specific variation of the script, the speed is exactly 60 because that's what is required for the two objects to intersect for a single frame
const float SPEED = 60;
//Misc variables
Vector3 trajectory = Vector3.forward;
// Update is called once per frame
void LateUpdate()
{
//The idea is that, after everything else in the scene has moved, the projectile checks its immediate area and trajectory for anything it can hit
//If it does, I should get a message telling me something was hit
//Otherwise it moves to the next spot along its trajectory
bool immediateArea = Physics.CheckBox(transform.position, Vector3.one * 0.5f, transform.rotation);
bool movePath = Physics.BoxCast(transform.position, Vector3.one * 0.5f, trajectory, transform.rotation, SPEED * Time.deltaTime);
if (!immediateArea && !movePath) { transform.position += trajectory * SPEED * Time.deltaTime; }
else { print("Collision detected"); Destroy(gameObject); }
}
}```
While the other has not just a collider, but a rigidbody attached and is traveling perpendicular to this projectile at the same rate meaning they're meant to theoretically overlap perfectly at a single point on a single frame. However during and after that frame there is no recognition from the above script that an object with not just a collider but a rigidbody ever crossed its path. I thought this might be an issue with ordering so I tried having this script run in LateUpdate but there's still no recognition that it ever hit anything. Why is this?
Check the logs, are there any errors? If not, add some log messages to your IPointer handlers and see if they're being called at all on Android.
some basic precalc stuff. any point on a circle can be represented by the parametric equations x = cos(theta), y = sin(theta). there u go
is anyone really familiar with platform effector 2d one way mode? Im trying to fine tune this to be more precise. Basically what I'm facing is there is a sweet spot the player can hit where its triggering my grounded check on the relevant collider but is not triggering the effector one way activation
Hi @vague basalt & @hybrid wagon , I fixed it, yeah the height is the problem since it's not being considered
my problem now is how to not get the guns, go through or pass through the body
happy to hear that
how do i make the "* new Vector3(0, 0, distFromRightPivot);"
local to rightpPivots[0].transform
rightPivots[0].transform.localPosition = rightPivots[1].transform.localPosition + Quaternion.Euler(remap(.37f, .5f, 0, 40f, -rightIkTarget.transform.localPosition.z, true), 0, 0) * new Vector3(0, 0, distFromRightPivot);
Hey, any ideas on how to scroll a scrollRect to the bottom?
So far anything I tried doesn't work, even forcing update canvas.
scrollRect.verticalNormalizedPosition = 0;
IEnumerator ForceScrollDown()
{
// Wait for end of frame AND force update all canvases before setting to bottom.
yield return new WaitForEndOfFrame();
Canvas.ForceUpdateCanvases();
scrollRect.verticalNormalizedPosition = 0f;
Canvas.ForceUpdateCanvases();
}
hey all, i just updated my project from 2020.3.x to 2022.3.42 (latest LTS) and i'm seeing something strange on my android build. i'm curious if anyone else experienced this. basically:
- Any audio played on AudioSource without loop checked doesn't play
- Any audio played on AudioSource with loop checked does play
to test this specifically:
source.loop = true;
source.Play();
source.loop = false;
when i added loop = true just before hitting play, it works (i just have to turn it off right after so it doesn't actually loop). is this expected behaviour in 2022.3.x? there's no issue with audio in editor - this is happening with android builds on device
I'm doing a sidescrolling game where you also can move up and down (representing fake 3d depth), classic 2D adventure.
Is there any builtin for 2D that helps with the Sprite Renderer's "Order in Layer"?
Right now I'm manually sorting the different sprites so the Box Colliders with the lowest Y gets in front of the ones higher up on the screen. But I'm not the first to make this kind of game, so I'm thinking that maybe Unity has something smart built in?
Possibly your source was already playing. Did you assign the clip directly on the line above? Does your source have Play On Awake enabled?
Mind that source.Play() internally calls the drivers etc (same with video etc), so it's no big surprise it behaves differently in different devices.
are you saying though that 2020.3 didn't have this issue and 2022.3 does?
Yes! Project Settings -> Camera Settings -> Transparency Sort Mode [Set to Custom Axis] -> Transparency Sort Axis [Set to (0, 1, 0)]
term you might be looking for is isometric top-down for your camera setup
Big thumbs up, gonna have a look, thanks
np!
Wow, seems to work out of the box, such a relief to scrap all my ugly code for doing the same thing 🙂
was unsure whether the correct axis is (0, 1, 0) or (0, -1, 0) but nice 😄
but yeah you can be describing it like this to google/people here
In my mind isometric isn't exactly the same thing, but I might be wrong
When I think isometric i think kinda tile-based stuff, but yes, it's probably the same thing, just my perception of it being something else
the source wasn't already playing - i checked. it doesn't have play on awake either. and yes i assigned the clip just above it
yes, the upgrade changed the behaviour
If you'd be as kind as to report that to the Unity team then it'd be nice 😛
No errors, they aren't even being called I checked it out with logs
I need to create a script where the player has money and can buy guns off walls
That's not one script, that's a whole system
Involving many pieces
Also don't crosspost
3D? You could do it with a raycaster. Cast a raycast from either the players head, or the players mouse(i dont know how your game is played). If that raycaster is hitting the gun on the wall, and you press click you can call a function that checks if the player has enough money and handles the buying for that gun. You need to do this in multiple scripts as well
you really didnt even read the command linked in the other channel or the #854851968446365696
Have you built the inventory system already?
Because when you can build that, the rest should be easy
Hi! How you guys document/comment your code flow. Imagine you do a Save system, you guys just comment in the code, or use an app like obsidian and explains like "Ey this Manager wil call this so this can be used and this will happen if this is being..."?
for your own project, or some package that'll be used by others?
For your own project, its not really needed and you'll probably be writing it somewhere when designing the game.
For the latter, i typically see people do stuff similar to the unity docs, or just a straight up PDF in the package. Even unity's ngo has their own docs for it https://docs-multiplayer.unity3d.com/netcode/1.1.0/tutorials/get-started-ngo/
comment in the code. Each type & each public method should have a /// <summary> block
and each algorithm that's not self-explanatory should contain enough // comments to make it skim-throughable
explaining private fields with summary blocks is overkill imo. A comment at max IF AND ONLY IF the name isn't self-explanatory, or ambiguous with another variable.
if we're talking about like the flow of the game, which is what i assume from their example, its kinda hard to just put that above a method. It wouldnt always make sense to say "a manager will call this function" and you wouldnt exactly comment it in the managers code cause you would see it called. Otherwise you start to end up with
int a = 1 + 2; // a is equal to 1 + 2
although the question also makes me think this is for other people, so id really suggest just making a unity style doc or a pdf
public fields/properties you might or might not wanna document based on your plans for the game. Is it a long-term project that you intend to review after years?
If so try to solve the issue via architecture first (e.g.: stop needing this as public), and if everything fails, commenting wouldn't hurt too much.
The issue with commenting public fields/properties is that it'd be inconsistent if you only commented very few of them, so you might have to comment everything afterwards
Nope, just a solo dev and own project
Then simply dont worry about it. Comment stuff that you'd possibly not understand in a week or month using the summary blocks.
I kind of do that and I don't really mind if it's stuff I'll instantly recognize if I see this after say 5 years
e.g.: I'll always know what temperature is, but singleLine and preventRefusals can be easy to forget, so I'd rather just look at the comment and know instead of having to go through the code flow
Here's another example lol https://github.com/Lyrcaxis/Llamba/blob/main/Batching/ContextRefresher.cs
This'd be terrible if I forgot what some lines of code did. I made it so I can understand the whole code by just reading the comments.
I'd also need comments if i was trying to read code formatted like this.
Yeah I like my code dense lol.. I hate scrolling after a wrist thing I obtained
anybody here knows how i can access snap settings?
I have pg up and down binded to mouse buttons, could be useful for you
Okeys, thanks @lean sail @stable osprey
can anyone help me here?
And that whole system falls apart and becomes usless as soon as you change anything in the code and 'forget' to update the comments
why would you forget to update the comments lol
haste
we have a system built into our version control system. You have to update the documentation BEFORE you can check out the code for modification
I can't fix this error, what do I change? The GroundDistance or the CheckSphere
that's pretty cool
would probably work best with a dedicated architect in team though -- which is kinda rare from what I see lol
and if I increase the GroundDistance the player will like flying
well, you can fix your issue by making sure the isGrounded bool is true when it has to be.
So I'd say keep an eye on that bool and make changes until you get it right 😛
that said, each of the parameters there are to be checked and tuned. Starting with the groundMask -- is the sloped platform part of the Ground layer?
yea
i set this thing to global but it wont let me open the grid snapping
not a code question
I already set all of the Level to Ground
whats a good channel for this question?
what about this one?
Hello, I am trying to make a voxel system similar to Minecraft and I am working on the textures for the blocks. This is my code that generate a texture atlas:
public void CreateAtlas()
{
uvRects = textureAtlas.PackTextures(Textures.ToArray(), 1, 2048); // uvRects is a Rect[]
}
And I am getting the rect from a Rect[] using this method:
public Rect GetTextureRect(string name)
{
var index = Textures.FindIndex(0,x => x.name == name);
if (index >= uvRects.Length || index < 0)
return default;
return uvRects[index];
}
This method applies the UV to the blocks:
private void AddTexture(string textureID)
{
var uvRect = BlockSystem.Instance.GetTextureRect(textureID);
uvs.Add(new Vector2(uvRect.xMin, uvRect.yMin));
uvs.Add(new Vector2(uvRect.xMax, uvRect.yMin));
uvs.Add(new Vector2(uvRect.xMax, uvRect.yMax));
uvs.Add(new Vector2(uvRect.xMin, uvRect.yMax));
}
It does apply the texture on each block, but it seems to be sideways and stretched (shown in the attached image).
could rotate the UVs until you get this right, or adjust the shader (probably the UVs though)
yep it's already Ground
then now you can change the other variables -- like groundCheck.position, and groundDistance
moving groundCheck object up or down a little should fix it
if I increase the Ground Distance it will work, but yea as I said the palyer will fly
just make sure it won't break too much
kk lemme try
I'd start with the groundCheck object
where is your collider in this?
the player? or the groundCheck
the collider on that floor tile because I dont see the gizmo in your screenshot
box collider?
it has a boxcollider
I know it's a box collider, I can see that in the Inspector, but I dont see it on the scene view
ok, that good, so If you want to Raycast from the player to that floor tile your cast direction should be -floorTile.transform.up so you are raycasting down taking into account the slope of the floor tile
then your ground distance is no different than if you were walking on a flat tile
Is there a smooth way to retrieve a field from a list, where another field is x?
Pseudocode for what I want:
myhp = List.Find(Character = gameObject, characterHP);
I'm doing this with for-loops at the moment, iterating through the entire list. And I have a feeling that there is probably a better way which I have yet to grasp 🙂
nope that is the best way if you use a List, you might want to consider using a Dictionary instead
Is there a way to move rigidbody to a new position with triggering collisions along the way? I'm making a hitbox collider that should deal damage to the enemy on OnTriggerEnter(), but if the animation of the movement is too fast - it phases right through the enemy and doesn't do anything.
void LateUpdate()
{
//_hitboxParent is the bone Transform which the hitbox is supposed to follow in the current attack
if (_hitboxParent && data)
{
// tried this
// transform.position = _hitboxParent.position;
// and this...
// transform.position = Vector3.Lerp(transform.position,_hitboxParent.position,0.75f);
// this doesn't work either...
GetComponent<Rigidbody>().MovePosition(_hitboxParent.position);
transform.rotation = Quaternion.identity;
if (!_hitbox.enabled && timeSinceAttackStart > data.attackDelay)
EnableHitbox();
if (_hitbox.enabled && timeSinceAttackStart > data.attackDelay + data.attackDuration)
DisableHitbox();
}
else
{
transform.localPosition = Vector3.zero;
if(_hitbox.enabled)
DisableHitbox();
}
if (debug)
DebugEx.DebugLocalCube(transform,_hitbox.size,_hitbox.enabled?Color.green:Color.grey,Vector3.zero,Time.deltaTime);
}
The list contains a lot of stuff, like GameObject, instantiatedObject, bla bla. I think Dictionaries can just be two items, like string and value? I don't really comprehend how this can solve my problem, but I'm sure it can. You have any resource which can help my old brain understand?
what type is characterHp ?
It's int, so I understand that somehow it could work, I just can't comprehend how. Or well, I could put it "outside" of the CharacterInstance object, but I feel that it'll get more complicated?
This is the CharacterInstance:
{
public CharacterData characterType;
public bool inUse;
public string owner;
public int hp;
public InputController inputController;
public GameObject instantiated;
public CharacterInstance(CharacterData characterData, GameObject instanceOfCharacter)
{
characterType = characterData;
hp = characterData.basehp;
inUse = false;
owner = null;
inputController = null;
instantiated = instanceOfCharacter;
}
}```
(It maps a character to a player, and it also holds hp of character, and maybe more stuff in the future)
ok
Dictionary<int,Character> myDict
...
myDict.Add(gameObject.characterHp, character);
...
Character character = myDict[gameObject.characterHp];
Dude I just wanna buy you a beer now
I don't fully understand this yet, but I feel that it'll soon click 🙂
I prefer red wine, thank you
That makes us two. 😉
in case you want the original version of your pseudocode as well, you can write it as List.Find( item => item.Character == gameObject).characterHP;
it might be faster to use a dictionary if you have lots of entries, but this is simpler and uses less memory, so as always you'd want to use the profiler to decide if performance is an issue
https://docs.unity3d.com/ScriptReference/Rigidbody.SweepTest.html
Are you looking for something like this? What you're describing (and the code) doesnt really make much sense. Animation doesnt use rigidbody movement. You'll need to use the physics queries likely or mess with the collision detection mode on the rb
Awesome! I'll try to grasp how to use Dict from SteveSmiths help, since I certainly will need to understand it. But might implement your solution as well, since it looks super slick.
What you're describing (and the code) doesnt really make much sense. Animation doesn't use rigidbody movement.
Hitbox is a separate script that follows a set transform. In this case it's a bone of a character. What doesn't make sense here? How would you do it?
I tried to use SweepTest, but now I have a super weird issue that SweepTest result colliders don't have attachedRigidBody defined for some reason, so I get null reference exception errors in OnTriggerEnter():
Vector3 oldPos = transform.position;
transform.position = _hitboxParent.position;
var hits = GetComponent<Rigidbody>().SweepTestAll(transform.position-oldPos,(transform.position-oldPos).magnitude,QueryTriggerInteraction.Ignore);
if(hits.Length >0)
foreach (RaycastHit hit in hits)
{
if(hit.collider != null)
{
OnTriggerEnter(hit.collider);
}
}
private void OnTriggerEnter(Collider collision)
{
// stop hitting yourself! This if is generating null error
if (collision.attachedRigidbody.transform == _owner.transform ||
collision.attachedRigidbody.transform == _hitboxParent.transform) return;
TryDoDamage(collision);
}
Only one side of a Trigger or Collision has to have a Rigidbody, so if this object has one then the chances are what it hits does not
Oh, good catch, TY, noticed that I'm getting errors when trying to attack a wall as well.
lol, in my experience attacking walls only leads to concussion and a short hospital stay
The script implementing the handler interface is on a UI element, yes? It needs to be.
Are you getting any other types of touch input in your build? Try logging Input.touchCount. Add a default UI Button - does it register taps? Do you have an EventSystem in your Scene? Is Block Raycasts enabled on the UI with the handler Script on it? Is there a Graphics Raycaster component on the GameObject with your Canvas? Is there another UI element in front of it preventing Raycasts from hitting it?
So I'm making an online board game and I want to code a check to highlight a circle in the gameboard grid. I have a point for each grid and it has a highlight object. How can I do this check?
something like this
and it highlights the nodes in that area
What do you mean by highlight, im having trouble understanding what you want to do
activate an object in each node
Simple math
you have a central point of the circle
You have the radius of the circle
So you have the area covered by the circle
Each node should change if it falls within this area
so I have to make a new variable?
how can I see if it falls in this area. I have an int to show what column and row it is on?
it's basic math
https://math.stackexchange.com/questions/198764/how-to-know-if-a-point-is-inside-a-circle
You'd need two integers unless this is based on a single dimensional array.
yeah I have an integer for both
this works perfectly I'm gonna try it
can u fix?
I don't have OCD but watching this image for too long might give it to me lol
That's simpler than it sounds:
var hitObjects = FindObjectsOfType<Highlighter>().Where(x => Vector2.Distance(x.transform.position, mouseWorldPosition) <= radius);
foreach (var highlight in hitObjects) { highlight.Highlight(); }
You could also go with physics if you got colliders:
var hitObjects = Physics.OverlapSphere(....);
foreach (var obj in hitObjects) { obj.GetComponent<Highlighter>().Highlight(); }
but your objects are very weirdly positioned. As in they don't appear to be on the center of their grid cell.
it's cause I had a tilted view
The circle doesn't seem good. I had to change the code to be d <= radius to get this result in the first place but I don't know what I'm missing``` var radius = DistanceMultiplier;
for (int i = 0; i < SpawnedMap.Columns.Length; i++)
{
for (int i2 = 0; i2 < SpawnedMap.Columns[i2].transform.childCount; i2++)
{
var d = Mathf.Sqrt(((Col - i) * (Col - i)) + ((Row - i2) * (Row - i2)));
if (d <= radius)
{
SpawnedMap.Columns[i].transform.GetChild(i2).GetChild(0).gameObject.SetActive(true);
}
}
}```
use a Gizmo to draw your circle so you can visualize it
Does destroying a UI Button automatically clean up any Listeners it has added to it, or is that something I have to manage myself on destruction?
no, you must do it manually
so I draw a sphere with the radius?
no, a circle
ok
my code doesn't compile nor it reloads domain after i close the code, my script has no errors nor warns.
i tried reopening unity
but didn't work
Second question, is there a way I can remove listeners/callbacks that were added through scripts, but keep the ones made from inspector?
any help y'all?
you can ONLY remove those added via code
gizmos.drawX doesn't seem to have a circle
Oh you're right. I was running into a problem, but I was using wrong prefab @_@
then use DrawSphere
ok
I have a feeling that this is an ugly way of getting a reference/pointer/whatisitcalled to the weapon I'm about to swing:
WeaponObject = this.transform.Find("weapon");
While it works well, and I'm not sure that it is ugly, I kind of don't like the free text search for my weapon like this. Anyone who can point me in the direction of best practice?
First is when its 1, second is second, third is third. I can't really show it properly as its using the columns for making the circle and not the actual distance of scene
Assign the reference in the inspector.
Such an easy and obvious solution. Thanks a lot!
try hitting ctrl+R manually while having Unity focused
yea i fixed
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi, lmk if you still need help -- I really like your PFP and would like to find out whether which character it is or who the artist is if you don't mind sharing
code here
why does my script have an error in line 16 ? "Vector3" does not contain a constructor that takes 4 arguments.
here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Floater : MonoBehaviour
{
public Rigidbody rigidBody;
public float depthBeforeSubmerged = 1f;
public float displacementamount = 3f;
private void FixedUpdate()
{
if (transform.position.y < 0f)
{
float displacementMultiplier = Mathf.Clamp01(-transform.position.y / depthBeforeSubmerged) * displacementamount;
rigidBody.AddForce(new Vector3(0f, Mathf.Abs(Physics.gravity.y), displacementMultiplier, 0f), ForceMode.Acceleration);
}
}
}
i am following this tutorial: https://www.youtube.com/watch?v=eL_zHQEju8s
In this tutorial you'll learn how to set up boat movement and dynamic water physics in Unity.
Check out my devlogs: https://www.youtube.com/playlist?list=PLXkn83W0QkfmQI9lUzi--TxJaOFYIN7Q4
⎯⎯⎯⎯⎯⎯
Catlike Coding's article about shader-based vertex manipulation and Gerstner waves: https://catlikecoding.com/unity/tutorials/flow/waves/
Discord s...
we don't know what line is line 16
lemme type it
however you pass 4 parameters to the new Vector3() constructor, but it only accepts 3 (one for x, one for y, and one for z)
rigidBody.AddForce(new Vector3(0f, Mathf.Abs(Physics.gravity.y), displacementMultiplier, 0f), ForceMode.Acceleration);
the draw sphere didn't show anything and the problem is still occuring
oh so how do i fix it?
you find the excess parameter and delete it
it can be any of the 4 parameters here, probably the last 0f
so i delete it then
yeah but take a minute to find out WHY
steve I think I fixed it I remoeved the <= and just added 0.5f to the radius
on the contrary, it shows exactly that you are using the incorrect positions for calculating whether the point is inside the circle
I'm using the int grid I have to detect the circle
this is with a radius of 2 and its way much better
so how do you account for this?
wdym?
you are clearly highlighting something outside the circle
because the radius for the overlap sphere doesn't match with the grid radius
I have the radius set for 2 tiles but for the sphere its just a scale factor of 2
so the sphere wasn't catching up
I have no idea what you mean by that
so I have an int for the column and an int for the row. I make a circle with those ints and expand with that. But the gizmo is taking the same radius I use for the grid without any other scaling. So its just aimlessly growing in size
NO! It's because the other values are the X, Y, and Z you want.. the 0f just doesn't have any meaning there 😛
You were likely supposed to MULTIPLY the gravity by the displacement multiplier
i fixed it
as expected from the real vsauce 
fixed
yes 😈
keep up the good videos coming man
Trying to code some smarter AI, basically, I wanted to have them locate a point on a Navmesh, where they can see the player to shoot them.
I thought I was being somewhat smart by creating a bunch of nodes (Spacing defined) on a Navmesh, and looping through them every X frame to see if they could shoot the player, however, the problem is I'm doing roughly 2300~ Raycasts (Potentionally more.) Every X frame.
Anyone have any thoughts on a better way to handle this I suppose?
Lets say there is a class A. A contains a string, and I want to be able to access a specific A with the specific string. Should I use a dictionary<string, A> or just have an list<A> and use LINQ to access that specific A? I'm asking in terms of performance
Dictionary and it's not even close. Linq is not any faster than iterating through a list normally. Dictionary access is O(1)
You might use a single Linq query to initialize the dictionary, if you already have a list of A that you want to turn into a dictionary, but your individual access should be through that
One more question: There is a dictionary<int, A> with 100 key value pairs. I also want to have a list with some of the A's from the dictionary. Should I just make a list of ints and access the A's through dictionary[int] or could I have a list of A's? I'm guessing list of ints is better performancewise since the classes hold references
no difference except in memory usage, a List<A> will occupy twice the space of a List<int>
Yea ty
it's not exactly wrong to say dictionaries are generally better, but it depends on other factors too - O(1) only means it'll scale well with lots of elements, but if your list is small then linear search (with LINQ or otherwise) may actually end up faster, see the first answer here https://stackoverflow.com/questions/908050/optimizing-lookups-dictionary-key-lookups-vs-array-index-lookups
definitely not small
There was no indication that a search would be getting done here
The question is missing context
We don't know the access patterns intended
As far as I understand you're debating keeping the int key of the dictionary vs a direct reference?
right, but you might want to profile it to confirm the numbers rather than relying on theory!
What would be the point of keeping the dictionary key? It seems like just a useless indirection here unless there's some other reason to use the int key instead
wdyym
Since the dict key would just lead you to the reference
so in that case list would be the same?
Am I correct on understanding your question here? #archived-code-general message
Ok so let me rephrase to clear any doubt
In what case? Again it's hard to say because we have no idea what you're doing with the list
Oh I just reread this... Definitely use a dictionary
I think you read my second question wheereas simonp answered my first question
I was asking this
Oh yeah I was answering this at first
I don't see any reason not to just have a list of the class references in that case unless you wish to be able to remove things from the list based on the int key or something
I have a 2d game that needs to have a perspective camera sometimes. For those cases, I transtion to a 3d camera by using a very low FOV perspective camera to mimick 2D. This works but the camera distance required is very high(>8000, FOV = 1). Are there any floating point or some other issues with using a perspective camera with such high distance?
The transform.position.z of the 2Dsprites are unlikely to be more than 40. So basically total camera to object distance is never more than 10,000 on the z axis. I also do screenpointtoraycast but that hasn't been a problem(yet). Is there any other risk at using a perspective camera for a 2D scene at such high camera distance(ex: floating point)?
Why not just change between orthographic and perspective mode though?
It needs to be smooth.
cinemachine blends don't work between ortho and pers
makes sense ig
I'm asking about stability of low FOV high cam distance perspective camera for 2D scenes because I'm thinking about ditching ortho camera for it. I have a lot of issues with 2D sorting with ortho camera. But no sorting issues with pers. I also have to make compatible with both.
What sorting issue are you getting? The two camera types shouldn't really affect that.
8000 is quite far yes.
It's less sorting issue and more that I need to change which stuff can show above others very frequently. With pers I can just set z pos
I don't know enough about the way unity cameras work to be able to answer the precision issue question but if you want an alternative solution, actually there is one other way but it is a bit of hassle to get working. The way it would work is by setting Camera.projectionMatrix to a custom matrix which can be lerped between Matrix4x4.Perspective and Matrix4x4.Ortho. I did that in one of my projects but it's couple years ago so don't remember any specific details. I think I did that by just lerping the individual elements of the matrices to get the final matrix
You're not going to get into floating point issues with the objects themselves but you might experience issues with depth sorting. To even render stuff that far you're gonna need to up the far clipping plane.
The range of the clipping planes I BELIEVE defines the range of the depth buffer. The bigger it is the farther objects need to be to avoid z-fighting.
Yeah I set it to 10000
If you keep the clipping plane range small it should be alright? I'm not completely versed in this.
I noticed that the z diff needs to be pretty high to sort properly
Messing with the camera projection matrix like @maiden fractal mentioned is probably the "correct" way to do this.
Like when I think high distance low FOV cameras I think FoVs of 5 and distances of ~100.
So 8000 is pretty nutty.
The other reason i want to switch to pers cams is sorting layers. I haven't used them in this project but I've heard that sorting layer is prioritized over z distance in ortho camera. This'd be problematic as I'd need to replicate sorting layers for each z axis layer after moving objects.
It'd be better to just switch over to pers camera now if that's the case.
Are you visualizing sprites or opaque meshes?
Just tilemap layers. Like this:
https://www.youtube.com/watch?v=0Eph3Ci9cyM
Except you can mess up the layers.
The world is ruined; mankind is gone and all that remains are robots. But for Poncho, the adventure is just beginning! Explore an open world full of colourful characters, leaping between parallax layers to overcome obstacles and solve puzzles. Can you make it to the Red Tower, meet your Maker and ultimately save humanity?
Subscribe for more Nin...
Everything is sprites. No meshes
Ok I think I messed up a bit on the FOV calc. It's ~800 ish camera distance on the z axis not 8000. Is that still bad?
I dont think you should need to loop through every node, just the ones that are around the AI that is intended to have line-of-sight (LOS) with the player, another option if you dont have many AI, is to fire a linecast from your AI in the direction of one of your nodes or from a global player reference, if it hits something that is not the player then there is no LOS, otherwise if you have a lot of AI your node system sounds like a scaled approach that can allow a hivemind-type manager to update your AI
There might be some misunderstanding here.
So the idea being is each node updates when the player moves, to inform the AI that they could be in LOS of the player at the node. The AI then moves towards that node to shoot the player.
If the AI was more dumb, it could, in theory, just run towards the player and shoot. However, in tighter corridors/objects blocking/etc, it could end up behind an obstacle shooting or just picking random points until it happens to be in LOS.
In terms of it being a "Hive Mind" these nodes are already updated in a single instance, not per AI. Each AI has access to these nodes and they're not running the checks individually
(Yellow indicates they can shoot the player from that position. Green is a higher priority in terms of the position where they should go, Red means they can not.)
And the reason for Yellow vs Green at the end of the day, is due to the fact that in some levels, the AI can't directly walk towards the green location, but they can still shoot the player. As such, they should still shoot the player.
I wrote this #🖱️┃input-system message in #🖱️┃input-system but I think is 70% #archived-code-general if someone can help 🙂
Ah I see, if you already have a Hive Mind-like structure I think your approach seems fine, if you absolutely have to update every node every x frames, a raycast does sound like the go-to approach, otherwise maybe you could try something similar to A* with distances/scores and neighbors, or store the nodes in a collection type that can remove nodes with a score of 0, for example if all your AI and player is generally in the center of your map, its unlikely the nodes at the edge of your map need to be updated as even if the player moves, it wouldnt be a scenario your AI could see a score above 0 for those nodes, it might not help by a large amount but could cut maybe 15% of your node loop
Your question seems to be mostly related to the use of the input system through code, so its fine to keep it in the input system channel
Hi folks, I don't exactly know where to post my question, as it seems both trivial and difficult at once:
I'm having a class implementing the Singleton-pattern. Let's just call it the class "Singleton". It is written as followed:
public static Singleton Instance { get; private set; }
void Awake() {
if (Instance != null && Instance != this) {
Destroy(this);
} else {
Instance = this;
}
}
}
I have two Scenes, A and B. Both scenes contain a GameObject with the Singleton-class attached.
Scene A starts first and sets the Instance to it's GameObject. The moment I switch to Scene B, the identical GameObject is also settings it's Instance.
Now as I switch from Scene A to B, the static Instance is "transferred" to Scene B and persists separately from the Instance in B.
This is a huge problem for me, because I expected the Singleton-class in Scene B to auto-detect that Instance has already been set in Scene A (as the Awake()-method intentions). But now I have two entirely different Instances running during Scene B.
Especially cases where the Singleton has a reference to another (non-persisting) GameObject are bad, because the moment I switch scenes, the Singleton throws errors.
Is that a known bug or did I miss something crucial regarding the creation of Singletons in Unity? Is there a proper way to remove an "old" Instance from a previous scene?
I tried a cheap shot with destroying the Instance with OnDisable(), but that's too shady to do
Usually it's the "old instance" that's kept, and the ones that are trying to be created in further scenes, destroyed
You do Destroy(this), so you'll still see the object in the hierarchy but it won't have the Singleton script on it.
Use Destroy(gameObject) to destroy the whole object
Persistence through scene changes should be made with a call to DontDestroyOnLoad(gameObject) in Awake, right after you assign the static Instance property
This transfers the object to a scene that's never unloaded, effectively keeping the whole object until you destroy it, or the game is closed
Yeah I got that far and that's what I sticked with, I was just curious if there was a way to keep an Instance per Scene, not across all of them. Thanks for your help though.
What I used to work with is a "GlobalAccessor"-class finding all GameObjects by tag and serving as a public connection between scripts, might stick with that again
This breaks the singleton pattern, it's not a singleton anymore if the static instance changes from time to time!
If you're not planning on transferring data between scene changes, you most likely don't need that persistence
But yes you can still use the pattern without the persistence, as long as all the references to scene objects are "refreshed" on Awake
My animated sprites works ok in my game, but is there any way to see the animations in the inspector? I have one that doesn't work well, and I wish I could find a way to preview it
(I havn't done any skeleton link animation stuff, just regular sprites from a sheet)
Select the object in the scene that has the Animator Controller, and from the Animation window, you should be able to preview the animations on your object.
-# Not a code issue, post further questions to #🏃┃animation
Hmm I don't have the object in the scene, I'm instancing it from my spawn-thingy 😐
The same can be done with prefabs, open the prefab and follow the instructions as usual
Oh, great, found it. Wouldn't have done it without you, big thanks! 👊
anyone here have any thoughts on using vs versus vs code? i've been using vs for forever but I like code for non-unity projects. Is the support good?
visual studio > vs code
Everything does seem pretty customizable and works well in vs, at least I don't have to restart it lol
For other languages, vs code will be used more.
A lot of languages will have extensions on it, when the language itself doesnt have a good IDE. Like when I used ocaml, the IDE at the time was worse than python IDLE
Hmm, yeah its still slowing down my game a fair bit, however, I narrowed it down to the NavMesh.CalculatePath call in my case. That appears to be causing the slowdown the most.
Each enemy is calling the following every frame. (Can be reduced TBF, hower I am still concerned it'll be a problem?)
NavmeshLineofSightHelper.Instance.HasPossiblePoint(agent, item)
Where that calls:
foreach (var item in tetherPoints[GetHeightModifierAsFloat(inShootHeight)]) {
if (item.canSeePlayer && CanReachPoint(inAgent, item.point)) {
return true;
}
}
And in this case, CanReachPoint is your standard NavMesh.CalculatePath.
I know in most cases, people just make AI go to player, but, trying to make things a bit more smart I suppose?
Seems the main cost was the Obstacle Avoidance Quality setting.
100 Agents on Screen, Floats around 60~ FPS (With Valorant open in the background in Editor.)
50 Agents I'm at around 140~
The downside to this: They have no Obstacle Avoidance tho.
Is there some option that allows the child transform to not inherit certain attributes of the parent transform? I don't want the health bar of the enemy to change scale (flip horizontally) but I want it to follow the position and be destroyed with the parent as usual.
you have to custom code that or use a constraint component
How can I convert a 3d render texture to a texture3d so i can write it out to a file? the async one that keeps cropping up online doesnt work, and given that render textures dont have any GetPixels or any similar methods I am kinda at a loss
you have to to make it the "active" one, then you can read its pixels
but you cant do that with a 3d texture right?
cuz readpixels only accepts a rect, which is 2d to read
there is a script that uses that that keeps popping up
it crashes my unity
maybe check your texture settings and driver/hardware compatibility
yeah
is there some event I can subscribe to when I add a new element to an array in the inspector? I know this is a long shot but
No. You could do your logic in OnValidate though.
Hello, I'm trying to segregate my player behaviors, and I'm used to using state machines but with Coroutines and collision triggers it's tough to really organize it the way I want to, are there more efficient methods to organizing conflicting player behaviors better than state machines?
I often make them states as well and have a mono as the "manager" for all of them, though my states are usually serialized classes so I can still set references from the inspector as needed, and pass events and properties around for everything else - another option you could look into might be with using interfaces, or possibly scriptable objects if you want to be able to hook up states on AI/non-players through the inspector or generate states and reuse them at runtime
So for example, i have a stealth action platformer where the player hides, attacks, and runs and jumps, and my current code is using booleans like hiding and attacking, but they often conflict and softlock my game
I would think your manager should have conditions to prevent conflicting states from playing at the same time, or you could setup some kind of structure (for example, maybe with a Dictionary) that would only allow certain states to play if they are considered "valid", your game logic would need to know that you cant be in a "stealth state" and a "attak state", but it would need to know what to do if you ARE in a stealth state and try to attack, some games may force you out of stealth in favor of the attack or just play a sound letting you know "thats not allowed, you have to change states manually"
Is Instantiating an empty GameObject and adding the required Components with the AddComponent method less performant than Instantiating a prefab directly?
Quick question, so I checked and apparently TMP does support little icons in the text, but can I make it use my custom icon provider?
For example: <sprite name="resources.gold"> 5000
and then it calls a function like this one: Texture2D GetIcon(string name)
or something like that?
I already know TMP has links which can trigger custom code, but can sprites be loaded from custom code like this as well?
May not make a big difference but there’s absolutely no reason to never do the former if the latter is an option. If you are concerned about the performance, create an object pool (multiple objects) or instantiate the object at start and hide it until you need it (one oject)
#📲┃ui-ux might be better fit
aight
Are you also aware of whether Instantiate creates an empty GameObject first, then copies the required parameters from the parameter prefab?
I’m not but in practise it doesn’t matter. Either way you should pool the objects rather than trying to construct the objects in code which is not very flexible way to do it. You can always make two versions and profile the performance but again, I dont see why you would want to do that
Got it, thank you for your help. I'm spawning Images inside of the object in the Editor for runtime pooling and consider getting rid of the image prefab, serialized in the Inspector
Can I somehow invoke an event outside of the class the event comes from? I need to check a bool but I also need the variables from the event which is a lil annoying
I should probably put a bit more.. onCoreSnapped has a parameter called "item" which I need to check before I do anything in the event. private void CoreModule_onCoreSnapped(Item item)
If that's a C# event, then it's not possible to invoke it from outside the class it was declared in.
Though you can create a method in CoreModule that does it for you, and call it in your piece of code here:
if (HasCrystalCore)
CoreModule.RaiseCoreSnapped(); // method that raises the event
I ended up just making a static variable of item that was set to null/not null when I need, then checking that like so. That does seem interesting but I'd still need to pass the variable from a separate event
if i have
public class MyBaseClass
public Instance;
public void Start()
{
Instance.DoThing()
}
public override class MyDerivedClass
public new Instance
those are two seperare vars right? what gets used in Start for derived class?
Instance of BaseClass.
That's bad practice though, using new to shadow base members
Sorry but that code is complete nonsense
howso
too many things to mention individually. Try and compile it
so there completely unrelated values yeah? just derived refers to the new one and not the base class unless explicitly using base.?
public override class 🤔
It's obviously pseudocode people
its meant to an example not 1:1
there are 2 different values yea
Yeah they're unrelated
you could, at least use correct C# syntax, so it is understandable what you are trying to achieve
nah its fine ty tho
I remember being yelled at for using static variables here, especially bools, but they've been working perfectly for each use case I have, is there some unwritten taboo about using them?
dont have the full context for this so might be bad response but in general ive never had a usecase where i needed to reference a value staticly where just a singleton for that class wasn't a cleaner option
nothing wrong about using static variables in the right use case, just be aware of the pros and cons
That seems pretty fair
I think it may be off-topic but I dont know where to ask.
My visual studio code enter key is "bugged". The bug only happens in one file with 1500 line + (I dont know if this is problem). What I mean is that normally enter key will start a new line without jumping your screen. But when I press enter, it goes to next line correctly, but it will jump the screen to a different line. Eg. I press enter in line 359, and after I press enter, the screen jump to line 399. How to fix this problem? it is so annoying. I now using shift + enter instead.
how can I make an algorithm of going through square grid from center to certain radius incrementally?
something like this
basically, need a "roll" of offsets
void spiralType(int centerY, int centerX, int maxY, int maxX, int type)
{
int y = centerY;
int x = centerX;
int da = 1;
fillSpiral(y, x, type, centerY, centerX);
while (y < maxY && x < maxX)
{
for (int i = 0; i < da; i++) fillSpiral(--y, x, type, centerY, centerX);
for (int i = 0; i < da; i++) fillSpiral(y, ++x, type, centerY, centerX);
for (int i = 0; i <= da; i++) fillSpiral(++y, x, type, centerY, centerX);
for (int i = 0; i <= da; i++) fillSpiral(y, --x, type, centerY, centerX);
da += 2;
}
}
void fillSpiral(int y, int x, int val, int centerY, int centerX)
{
if (y < board.n && x < board.n && y >= 0 && x >= 0)
{
// Your Code Here
}
}
sorry, but this is extremely confusing example
it's a simple spiral walk on the grid
if (y < board.n && x < board.n && y >= 0 && x >= 0) what's this for?
to make sure it does not go out of bounds of the grid
board.n is the width and height of the grid
so say, I just want offsets (meaning start is always 0,0)
void SpiralType(int maxY, int maxX)
{
int y = 0;
int x = 0;
int da = 1;
FillSpiral(y, x);
while (y < maxY && x < maxX)
{
for (int i = 0; i < da; i++) FillSpiral(--y, x);
for (int i = 0; i < da; i++) FillSpiral(y, ++x);
for (int i = 0; i <= da; i++) FillSpiral(++y, x);
for (int i = 0; i <= da; i++) FillSpiral(y, --x);
da += 2;
}
}
void FillSpiral(int y, int x) { }
start 0,0 would not make a lot of sense, that is the top corner of the grid
then you need to converr that to an array position because an array cannot have a negative index
all I need rn is just offset array
so smth like
[0,0;0,1;1,1;1,0 ..]
so then I can use actual center position
and simply do pos += offsets[i] in for loop
to get offset spiral position of grid
you can transform the y and x to anything you want in the FillSpiral method
seems correct
allthough I'm confused on maxY and maxX
because I got 1k elements
or is that how many I'll get
wait
those are the radius of the spiral
So I'm creating a 3D game where I want the player to be able to rotate on the x and y axis. I can get them both to rotate independently, however when they are combined, the rotation gets weird. I think its because when rotating on the y axis it takes both the horizontal input and vertical input even though it shouldn't.
Code: https://hatebin.com/pgvvhszrbq
your problem is you are using transform.eulerAngles as input data, you should not do this
what should I use instead?
you should maintain your own euler angles and use those
I'm sorry, I'm not sure what you mean by that
it means that instead of relying on getting the euler angles from transform.rotation. you keep track of them in your own variable
so like 'Vector3 Rotation = transform.eulerAngles'?
no, you're not reading what I have written
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
[SerializeField] private GameObject target;
[SerializeField] private float offSet;
[SerializeField] private float smoothTiming;
[SerializeField] private float minZoomOut;
[SerializeField] private float maxZoomOut;
[SerializeField] private Vector3 YTurn;
[SerializeField] private float maxYTurn;
[SerializeField] private float minYTurn;
float xMouse;
float rotateX;
float yMouse;
float rotateY;
float mouseScroll;
Vector3 currentRotation;
Vector3 velocityVector = Vector3.zero;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
}
void LateUpdate()
{
xMouse = Input.GetAxis("Mouse X");
rotateX += xMouse;
yMouse = Input.GetAxis("Mouse Y");
rotateY -= yMouse;
rotateY = Mathf.Clamp(rotateY, YTurn.x, YTurn.y);
mouseScroll = Input.GetAxis("Mouse ScrollWheel");
offSet -= mouseScroll;
offSet = Mathf.Clamp(offSet, minZoomOut, maxZoomOut);
transform.position = target.transform.position - transform.forward * offSet;
Vector3 targetRotation = new Vector3(rotateY, rotateX, 0);
currentRotation = Vector3.SmoothDamp(currentRotation, targetRotation, ref velocityVector, smoothTiming);
transform.eulerAngles = currentRotation;
}
}
Hello guys, I don't know why but my camera is shaking as i showed in video. How can I fix it? It's my camera script.
no need to reinvent the wheel, use Cinemachine https://docs.unity3d.com/Packages/com.unity.cinemachine@2.10/manual/CinemachineBodyOrbitalTransposer.html
or
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineFreeLook.html
you are a life saver, ill use this one but why do u think i have this problem in the video? I'd like to fix it if it's possible still
or I'd like to know the real problem
Hey there! Not sure where to ask this, but I was wondering if anyone knows any resources that I could check out that helps with making the game window an object that interacts with the game. Stuff like moving the window would make liquid in the game slosh around and such. If this isn't the place to ask, I'd love to know where I should direct this question! Thanks for any advice in advance!
incorrect values? bad code? I'm not sure tbh, I don't code cameras when I have CM
this would be quite complex to do, first you would prob need native DLLs or Library in the OS, each one handles window different
after that is just a matter of relaying that back to unity as input
Ahhh makes sense. I am aware what I'm asking for is pretty hard and probably super ambitious but I'm willing to try and learn from anything! Do you know a place where I could find more resources on the subject?
Actually it's not that difficult, you would need to create a wrapper around your game so that the game runs as a child process and your wrapper can detect window movement and then use something like a named pipe to communicate between the wrapper and the game. All fairly simple to make
for example . You can try checking https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowrect
The window rect and if it has moved to a different position since last check (maybe Update? might be costly) then it has moved
but yeah on windows is way easier
Is there any way I can take a high res screenshot of any editor window (not game view) ?
So I'm having a strange issue. I have the following set up in an animator. Idle -> Put Weapon away -> Put new weapon up -> idle. The transition from idle to put away is controlled by a trigger ChangeWeapon. away to up just has an exit time. If I manually click the trigger in the animator everything works. However setting the trigger from code like so HandsAnimator.SetTrigger("ChangeWeapon"); plays the away animation about halfway before getting interupted and snaping back to idle. Wtf ?
if I use a bool it all works as well
fuck me must be another animator bug....
In Unity Mathematics, is it possible to "scale" a quaternion. I'm storing a quaternion to represent an objects orientation, and another quaternion that represents its rotation rate... I was hoping to do _currentRotationQuat += _rotationRateQuat * deltatime; But I can't seem to scale the quaternion with a float no matter which way around I write it. Is this possible?
Use Quaternion.Slerp
Well adding quaternions together is not a valid way to combine rotation. You have to multiply them. In the case of Unity Mathematics, you have to use the math.mul method.
you could use Quaternion.Lerp or Slerp
slerp(quaternion.identity, myRotation, 0.1f) is 1/10th of myRotation
Can someone help me lower my unity batches
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
You need to be more specific. What render pipe are you using etc etc
Im using defaut render pipeline
i just get liek 8k for no reason
i wish someone would join call and just diagnoise why but apparently i cant ask that
Well a good way to diagnose this type of problem is to start turning off chunks of the level and see how the batch count changes
can also use the frame debugger
are there any issues with this that could possibly lead to json corruption/overwriting? very rarely my save will just wipe and I can't figure out why or whats causing it. The only thing I can think of is some issues with unity play mode after editing scripts (saving script while still in play mode causing a bunch of errors). I haven't tested it enough in build to see if the issue occurs there or what could even be causing it
The stream manipulation to create the file here is definitely not pretty - either use the stream to open, write, close in one go, or don't use it at all
im not super experienced with handling files with c#, can you explain what I could do better?
You can use a StreamWriter to wrap the stream, then call Write(json); NewtonSoft Json might even have an overload to take a Stream and directly write the JSON to it
okay, would that be whats causing the issue?
if not, how could I check if the data trying to be saved is corrupted and to not delete the file, because I believe that's whats happening
its just writing an empty file
Do you mean through a Editor script or through external applications?
this is my load function, maybe some issues here?
See https://stackoverflow.com/a/22689976 which has both the reading and writing logic using only streams
I have heard that Json.NET is faster than DataContractJsonSerializer, and wanted to give it a try...
But I couldn't find any methods on JsonConvert that take a stream rather than a string.
For
with editor script i mean i am trying to take a high res screen shot of a graph view in my custom editor window
As long as the using statements are used, the streams will be closed properly even if an exception occurs, ensuring the whole JSON payload (or nothing at all) is written and that the file handle is closed and disposed of properly.
so this instead?
That works - put the using line inside the try block to catch file creation errors though
Also use Path.Combine(Application.persitentDataPath, localPath) to build the path in a cross-platform manner
It overwrites, as specified by the File.CreateText() documentation
If the file already exists, it is overwritten
great thanks