#archived-code-general
1 messages · Page 288 of 1
One SO can act as the base class, other child classes can override and implement behaviour
alr ill try that, it sounds pretty plausible to implement
The only downside to this would be if you need a physical model in game paired with this effect
not really, you can always attach the SO instance to a gameobject that holds it as a data property
unless im missing some context, just peeked in here 😄
also another question how do you refer to the SOs, ive seen resources.load and stuff like that but it that bad in some way?
I just mean downside like its slightly more tedious because you need to pass around more data
You can drag it in directly to whatever needs it, to a field like
[SerializeField] StatusEffectSO statusEffect;
I'd only use resources if you need to load every single one and have like a random choice between all. Even then you could just drag every one to some list
What if i need to load a specific status effect from a script
just make a list of them in the manager and use that?
Then drag it in from the inspector, the same way you would drag it in if you needed to reference a specific prefab
you should create instances of SOs, unless you want to change the base SO, IIRC it even saves to file in the editor which you dont want 😄
I'm not entirely sure what you mean tbh, I dont use SO for mutable data
oh in that case its fine
Anyone have any idea why this recursive function is only Logging: 1 ? Objviously there is some issue with appending The list elements.. idk maybe new a async await? help
bool CheckDot(PointStruct point, Dictionary<Vector2Int, TileElement> dict)
{
int count = (int)point.data.dotIndex + 1;
int colorIndex = (int)point.colorIndex;
bool isActive = point.isActive;
List<Vector2Int> connectedPoints = new() { point.position };
Orthoganals(point.position, connectedPoints, dict, isActive);
Debug.Log($"{connectedPoints.Count}");
return true;
}
void Orthoganals(Vector2Int center,
List<Vector2Int> positions,
Dictionary<Vector2Int, TileElement> dict,
bool isActive)
{
List<Vector2Int> orthos = new();
Vector2Int up = new(center.x, center.y + 1);
Vector2Int down = new(center.x, center.y - 1);
Vector2Int left = new(center.x - 1, center.y);
Vector2Int right = new(center.x + 1, center.y);
if (CheckValid(up)) orthos.Add(up);
if (CheckValid(down)) orthos.Add(down);
if (CheckValid(left)) orthos.Add(left);
if (CheckValid(right)) orthos.Add(right);
if (orthos.Count != 0) positions.AddRange(orthos);
else { return; }
foreach (var item in orthos)
{
Orthoganals(item, positions, dict, isActive);
}
bool CheckValid(Vector2Int newOrtho)
{
if (!positions.Contains(newOrtho)) return false;
if (!dict.ContainsKey(newOrtho)) return false;
if (dict[newOrtho].isEnabled != isActive) return false;
return true;
}
}```
oh wait i think i know... let me check
yeah nvm.. simple mistake.. this is the broken code fixed for anyone wondering..
bool CheckValid(Vector2Int newOrtho)
{
if (!dict.ContainsKey(newOrtho)) return false;
if (positions.Contains(newOrtho)) return false; <-------------------- removed "!"
if (dict[newOrtho].isEnabled != isActive) return false;
return true;
}```
those if statements are some insanity
Im making sudoku,but clicking the cells isnt working.This is my cell script.The OnMouseUp() function ig isnt being called.Each cell has a 2D collider
using UnityEngine;
using UnityEngine.UI;
public class Cell : MonoBehaviour
{
public Board board;
public GameManager gameManager;
public Image cellImage;
public int row;
public int col;
public int value; // Current value of the cell (0 if empty)
private Color originalColor; // Store the original color of the cell
public void Initialize(int row, int col)
{
this.row = row;
this.col = col;
this.value = 0; // Initialize as empty
originalColor = cellImage.color; // Store the original color
}
public void SetCellValue(int cellValue)
{
Text cellText = GetComponentInChildren<Text>();
value = cellValue;
if (value != 0)
{
cellText.text = value.ToString();
}
}
public void SetValue(int newValue)
{
if (value != 0)
{
value = newValue;
// Update the cell's appearance based on correct/incorrect input
UpdateCellAppearance();
}
}
public int GetValue()
{
return value;
}
public void SetEditable()
{
if (value != 0)
{
// Change the color of non-editable cells
cellImage.color = Color.gray;
}
else
{
// Reset the color to the original color for editable cells
cellImage.color = originalColor;
}
}
private void OnMouseUp()
{
// Implement logic for when the cell is clicked
if (value == 0)
{
cellImage.color = new Color(187,222,251);
}
}
private void UpdateCellAppearance()
{
if(!board.IsValidMove(row,col,value))
{
cellImage.color = Color.red;
gameManager.IncrementMistakeCount();
}
}
}```
How do you know that it's not working? Add a debug log in the method.
Ok
I thought since the color doesnt change...
private void OnMouseUp()
{
Debug.Log("Cell clicked");
// Implement logic for when the cell is clicked
if (value == 0)
{
cellImage.color = new Color(187,222,251);
}
}
added this n ran it, nothing printed in the console on clicking
That's not an indicator. For example you could be setting color incorrectly(which you actually do). Then even if it was running, you wouldn't notice any changes.
im setting it incorrectly?!!
Iirc, you also need an event system with a physics raycaster in the scene to dispatch pointer events.
Yep. Check the docs for Color. It's supposed to have values in range 0-1.
You're basically setting a white color there.
ah
i c, the autocreated event system in mine doesnt hv that
Could be wrong though. Should check the conditions for OnMouseUp to be called.
It's poorly documented too. That's why I prefer IPointer handler interfaces instead.
Images? Ui images?
yea
Or Sprite renderers?
UI images
Then you don't need a collider
but they dont hv any source image
Nor physics raycaster
Wdym?
That's fine. As long as they're configured to accept raycasts.
ok
But I'm not sure OnMouseUp is called in that case🤔
so i can remove the raycast from eventsystem n remove the colliders?
Seriously, don't use it
what can I use then?
Does anyone know how to fix this issue with WebGL? 😅
So I have a bunch of AI controlled goobers. These goobers need to be able to interact with many different types of objects and perform associated tasks. For example, a goober sees a pile of wood and knows to pick up a piece of wood, take it to some specific location, and then return to the pile to repeat this process.
Any suggestions on how to set up this type of behavior? I have an idea of what could work, I just want to hear other options if possible.
I'm having a bit of a paradox issue here.
So, I have a script that adds valid items from one list to another list
Then, I iterate over that list, and remove certain entries from it.
The issue is, I can't seem to figure out how to do this without hitting invalid indexes, because List.Remove reshuffles entries in it when it is fired.
So I can't just save the indexes of the items I want to remove, and then run a for-loop to remove them, because when I remove one, all the ones ahead of it seem to be moving backwards in the hierarchy, mid-for-loop?
Do I just need to iterate over the entire list, and check against the values there instead?
What exactly are you asking about? Planning actions for the ai? An actions queue? Interaction system?
for (int i = 0; i < Container.Count; i++)
{
if (Container[i].item == _item)
{
_validitem.slot = Container[i];
_validitem.index = i;
_validItems.Add(_validitem);
}
}
for (int i = 0; i < _validItems.Count; i++)
{
Container.Remove(Container[_vIndex]);
}
Here's the gist of the code I'm using, trimmed down for ease of reading. I thought I could just save the indexes that I want to delete to a list, then delete them in a for loop, but that seems to be accessing illegal index values (I believe because the List is actually moving each time an entry is removed?)
public void RemoveAt(int index) {
if ((uint)index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_size--;
if (index < _size) {
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
Effectively the flow of communication. How is this task managed? How does the entity figure out what to do? It's kind of a board question because I'm sort of asking "Here is a problem, how would you guys solve it?"
Sounds like several systems working together: ai planning to decide on the actions to perform(could be implemented with state machines, behavior trees, goap, etc...) and action system for queueing and executing actions in order. Could also add interactables implementation to the list - the behaviour of the objects when interacted with by the characters.
My current idea is to have a list/stack of Tasks that the entity will do. Tasks are put on the collection and executed as a stack. Tasks themselves are like states with the usual OnEnter, OnUpdate, OnExit. Searching for an Interactable would be its own Task, and the interactable would be told "hey this guy is interacting with you" and it would decide whether to give the entity a task based on its ability/properties.
Logic within the tasks could get pretty complicated.
I could implement other AI planning logic in there if needed.
I like the whole "call/response" set up between the Entity and the Interactable.
It leaves all the logic of "Can I do this task?" to the interactable.
I don't know the whole context, so might be wrong, but in my opinion an Interactable object telling the character what it can or should do is not a great idea.
I'd have a set of actions/tasks defined for each character instead and they do their thing based on that.
If it has a woodcutting task, it would look for trees and start chopping them, if it has mining task, it would look for a pre, etc...
I guess for a bit more clarity, in my mind the interactable itself isn't the one giving tasks. More like there's a hitbox attached to the interactable with a "Task Giver" that is listening for requests and then specifying to the requester if/how they can interact with this object.
You mentioned you'd just define possible tasks for each character, but who is defining what tasks can be done? I think the idea of the entities and interactables just being a collection of stats/properties/tags directed by manager objects is probably the way to go?
The task giver is either you if the characters are in the scene from the start, or whatever spawns and initializes them. Or a system that orchestrates the movement/actions of all the characters.
If the interactables are the one that's gonna give tasks to them, how are they gonna know what Interactable to go to if at all? Would that need to be a separate system who's only purpose is to navigate the characters to the interactables? How is it gonna decide what Interactable to go to then? If each character has available tasks predefined, they can just select one and try to perform it based on the environment.
public void RemoveSlot(int _index)
{
List<SlotAndIcon> _SI = itemsDisplayed.FindAll(TrueIfNullSlot);
for (int i = 0; i < _SI.Count; i++)
{
Destroy(_SI[i].inventoryEntryObject);
}
}
Would this code snippet work for destroying a list of GameObjects? I'm worried the indexes might become invalidated mid-loop, and I can't find a method for destroying multiple GameObjects.
Is there a better way to destroy a list of GameObjects?
Alright listen. I was about to talk about how I would initialize each character with specific filters on their "InteractableSearch" task... but then I realized that's basically what you were saying to do initially >_>, so now I feel bad.
So for example a farmer character would only search for tasks marked as "Generic" or "Farming".
Haybales or whatever would be marked as a farming task, so the farmer would search for those and request an interaction.
They'd then be given a task that would coordinate the interaction with the Haybale.
So in that case I guess I'm still leaving the entities to decide what to do (what to try to interact with). It's just the interactable that confirms the request and specifies how to do it (by giving them a task).
Ah, in this case it makes sense. You wouldn't want to interact with an object that is already being interacted with. For example you wouldn't want 2 character to try and open a door at the same time or sit on the same chair together.
Hi, i have a problem. When my card is fragged, it won't play function that causes the card to be played. i have 3 scripts. Drop on Panel which receives dropping, card and drag on cards. Here are the scripts and the screens:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Drop : MonoBehaviour, IDropHandler
{
public Drag dragScript;
public void OnDrop(PointerEventData eventData)
{
Debug.Log("OnDrop");
if (eventData.pointerDrag != null && dragScript != null)
{
dragScript.DraggedOnPlace = true;
Debug.Log("DROP DZIALA");
}
}
}
public class Card : MonoBehaviour
{
public GameObject CanDragScript;
private CardGameManager gm;
public int handIndex;
public bool HasBeenChecked = false;
private Vector3 originalPosition;
private Vector3 enlargedScale;
private bool DescriptionActive = false;
private bool CanDrag; // Define CanDrag as a member variable
private void Start()
{
gm = FindObjectOfType<CardGameManager>();
CanDrag = CanDragScript.GetComponent<Drag>().CanDrag; // Assign CanDrag value
}
private void Update()
{
// Check if left mouse button is clicked and the card is not already enlarged
if (Input.GetMouseButtonDown(0) && DescriptionActive && CanDrag) // Use CanDrag here
{
// Perform default card click action
Debug.Log("Card clicked!");
transform.position = originalPosition; // Move to the original position
transform.localScale /= 3; // Decrease size by 300%
DescriptionActive = true;
CanDrag = true;
}
// Check if right mouse button is clicked
if (Input.GetMouseButtonDown(1) && !DescriptionActive)
{
CanDrag = false;
transform.position = Vector3.zero;
transform.localScale = enlargedScale;
}
}
public void PlayCard()
{
// Different outcome for every card
Invoke("MoveToDiscard", 2f);
}
public void MoveToDiscard()
{
gm.discardPile.Add(this);
gameObject.SetActive(false);
}
}```
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Drag : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler
{
public Card card;
[SerializeField]
private GameObject DropText;
[SerializeField]
private GameObject Drop;
private RectTransform rectTransform;
private CanvasGroup canvasGroup;
public bool CanDrag = true;
public bool DraggedOnPlace = false;
private void Update()
{
if (DraggedOnPlace == true && card != null)
{
card.PlayCard();
DraggedOnPlace = false;
}
}
private void Awake()
{
rectTransform = GetComponent<RectTransform>();
canvasGroup = GetComponent<CanvasGroup>();
}
public void OnBeginDrag(PointerEventData eventData)
{
if (CanDrag == true)
{
Debug.Log("OnBeginDrag");
canvasGroup.blocksRaycasts = false;
}
}
public void OnDrag(PointerEventData eventData)
{
if (CanDrag == true)
{
Debug.Log("OnDrag");
Drop.SetActive(true);
DropText.SetActive(true);
rectTransform.anchoredPosition += eventData.delta;
}
}
public void OnEndDrag(PointerEventData eventData)
{
if (CanDrag == true)
{
Debug.Log("OnEndDrag");
Drop.SetActive(false);
DropText.SetActive(false);
canvasGroup.blocksRaycasts = true;
}
}
public void OnPointerDown(PointerEventData eventData)
{
if (CanDrag == true)
{
Debug.Log("OnPointerDown");
}
}
}
Alright coolio. I'll give this a try tomorrow then. Thanks.
Just 1 more question though. Would the Task update take place in Update or FixedUpdate? Surely Fixed right?
It depends on what exactly you wanna do in the update.
Hi there is a System.MathF class with float versions of Atan2 etc. which seem like would be faster than Unity's Mathf that maps to Math double calls! Anyone compared and check Unity have no il2cpp speed ups for theirs?
ah FYI they do something clever in case of il2cpp to already use fastest methods
Architecture question. I have the current classes with responsibilities in a level editor:
-BuildingCreator: Parses player input, and sends commands out to BuildEditor, RectangleSelect, and PreviewManager.
-BuildEditor: Actually modifies level.
-PreviewManager: Updates/displays preview graphics.
-RectangleSelect: Handles area selection/copy/paste/move. Sends commands to BuildEditor. Contains a LayeredPreview to display what is selected.
-LayeredPreview: Displays a preview of a complex assortment of things.
Right now I worry that PreviewManager and RectangleSelect/LayeredPreview are fighting over the same responsibility. But I really need the machinery in LayeredPreview to be separate. Any advice?
I’m trying to avoid different classes tripping over updating preview graphics.
well for something like a level editor I'm partial to say that using 'mediator' and or 'command' pattern, would give you some good architecture
also makes stuff like undo/redo SO much easier
Hello guys i have a question what is better to achive ground check on 2D OnCollisionEnter2D or OverlapCircle()?
don't crosspost
all actual changes to the level must go through BuildEditor, which allows me to maintain the Undo/redo log
all input goes through the poorly named BuildingCreator so every frame has a unique single command of what needs to happen.
the main issue I’m foreseeing is that preview responsibiltieis become split because RectangleSelect needs to tell LayeredPreview what to display, because RectangleSelect keeps private data about what is actually in the selection.
This might be a bit of a tangent, and I might be in the minority here. But this is something I do that generally helps me organize the code better.
I find that most people read ‘X_Manager’ as the script that just does all things related to ‘X’. imo What you really have there is X_Hanlder, because it doesn’t manage code in the application, it actually handles / executes it.
I think a Manager class should just coordinate all the other smaller scripts that are responsible for ‘X’. So instead of ‘X_Manager’, you could call it ‘X_Cordinaor’ that coordinates ‘X_responsiblity_1_Handler’, ‘X_responsiblity_2_Handler’, ‘X_responsiblity_3_Handler’ etc.
So for a practical example: Building_Manager, manages: ‘BuildingHistory_Handler’, ‘BuildingPlacement_Handler’ etc. and Preview_Manager would handle both Layer_Preview and Building_Preview.
Note: the use of Cordinator, Handler and Manager here are just to illustrate a point. They mean completely different things given a specific pattern.
How would I count how many of a certain digit appear in a number?
Is there a specific function or will I have to split it into a list and loop it that way
textVariable.Count(c => c == specificDigit);
you have to be more specific about what you mean
is this a string?
Or an int or something?
An int
so you want to know how many 1s or 0s it has?
I just want to know how many 1s it has yeah
Ah perfect thank you
the absolutely fastest way would be to use the POPCNT instruction via System.Runtime.Intrinsics.X86
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.intrinsics.x86.popcnt?view=net-8.0
Of course, you'd have to test if the CPU actually supports that instruction and use a backup implementation if it's not supported
so earlier today i posted about my problem with clicking cells in a sudoku game to change their color, and i came around to use OnPointerClick() to do it, but still some of the cells dont change the color. The script is attached to every cell n each cell is the same except the row n column values.
In this pic the blue cells r the ones that changed color.
Also i need a way that when one cell is clicked all others go to their original color(ie only the currently selected one shld be of diff color).
You could add a Selectable to them
huh?
and use the selectable colors (it has normal, hover, selected and disabled colors)
oh btw my cells r all ui images
ohk
Add Component -> Selectable
ok ill check it out then
It will replace your pointer click thing
but any reason only some of them change?
No idea since you didn't share any code or other details
ok
maybe some are being blocked by something?
i just realised selectable is the thing automatically there on buttons lol
idk possible
ill try this
so ill hv to change the selected color or pressed color?
Button derives from Selectable yes
pressed is while you're pressing it
selected is after you pressed it
right
alr so i used selectable instead, but some of the cells r still not changing...
My guess is you have some UI blocking something
If you select your Event System and watch the preview window (bottom of the inspector) while the game is playing it should tell you which objects are blocking it
Oh ok
Trying to get a parallax to stop rubber banding. Not sure if its due to the transform position or something else
#🎥┃cinemachine message
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallax : MonoBehaviour
{
public Camera cam;
public Transform subject;
Vector2 startPosition;
float startZ;
Vector2 travel => (Vector2)cam.transform.position - startPosition;
float distanceFromSubject => transform.position.z - subject.position.z;
float clippingPlane => (cam.transform.position.z + (distanceFromSubject > 0? cam.farClipPlane : cam.nearClipPlane));
float parallaxFactor => MathF.Abs(distanceFromSubject) / clippingPlane;
public void Start() {
startPosition = transform.position;
startZ = transform.position.z;
}
public void Update() {
Vector2 newPos = startPosition + travel * parallaxFactor;
transform.position = new Vector3(newPos.x, newPos.y, startZ);
}
}```
Would love any help with getting this done. Also the channel redirect has a video of it
Can you show your player movement script?
Also - would recommend you use LateUpdate for the parallax script
Decision making for the AI essentially.
What to do next given the current task, if it should continue the current, etc.
Then either is fine I think. Could make a custom loop if you want to reduce the rate at which the ai updates too.
Wouldn't handling it in Update cause the AI's "thought speed" to be frame dependent?
Depends on your logic.
A standard timer where you accrue or decrement deltaTime would avoid that
Not necessarily. Imagine if the AI logic depends on a query into the game state (like distance to an entity). Handling that in update could lead to a miss as the entity moves.
private void Start()
{
rb = GetComponent<Rigidbody2D>();
playerControls = new PlayerInputs();
playerControls.Enable();
}
private void FixedUpdate()
{
Vector2 thrustInput = playerControls.Player.ThrustControl.ReadValue<Vector2>();
float SpaceBreakValue = playerControls.Player.SpaceBreak.ReadValue<float>();
float BoostValue = playerControls.Player.Boost.ReadValue<float>();
float yAxis = thrustInput.y;
float xAxis = thrustInput.x;
ThrustForward(yAxis);
Rotate(xAxis * -rotationSpeed);
if (SpaceBreakValue == 1) {
SpaceBreak();
}
if (BoostValue == 1) {
Boost();
}
ClampVelocity();
//Store ship data for UI
currentVelocity = rb.velocity.magnitude;
currentVelocityRaw = rb.velocity;
currentHeading = rb.rotation < 0 ? 360 + rb.rotation : rb.rotation;
}```
Removed some lines as its a lil large
Its all based on forces that impact the velocity
private void ThrustForward(float amount)
{
Vector2 force = (transform.up * amount) * thrustAcceleration;
rb.AddForce(force);
}
where does this get called?
In the FixedUpdate.
Oh wait I see it
No it wouldn't. Just queue it
I have a scrollpane with a few images to scroll through. I noticed however that a user really needs to click on the images to make the pane scroll. Is there an easy way to make the scrollpane also scroll when the user clicks in between the images?
I'm developing a racing game and I have an issue. When I drive the car, it rotates on the Z axis. I have the 'freeze rotation' option enabled on the Z axis in the Rigidbody, but it still rotates. Someone knows how i can fix it?
sounds like you're rotating it via its transform
Freezing it only prevents the physics engine from rotating it. IF your code is rotating it, it will still rotate. Also it only freezes on the glbcal z axis. Once you turn, that no longer is the one you are worried about
Could anyone please help me figure out how I deal with this error?
InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Input.GetKeyDown (UnityEngine.KeyCode key) (at <beffc13b4e034530abb1d1528533a5be>:0)
OVRLipSyncContextMorphTarget.CheckLaughterKey () (at Assets/Oculus/LipSync/Scripts/OVRLipSyncContextMorphTarget.cs:218)
OVRLipSyncContextMorphTarget.CheckForKeys () (at Assets/Oculus/LipSync/Scripts/OVRLipSyncContextMorphTarget.cs:154)
OVRLipSyncContextMorphTarget.Update () (at Assets/Oculus/LipSync/Scripts/OVRLipSyncContextMorphTarget.cs:131)```
It doesn't cause any actual issues because the game runs perfectly fine, but it makes debugging impossible since it clogs the console
The script comes from a library package so I didn't even write it
you could set the Active Input Handling setting in the player settings to Both instead of just the Input System
Yeah, that will let both systems function and suppress the error.
That looks like a "debug" mode that lets you preview different face morphs
So there may be a switch for it.
yeah the alternative would be to modify the asset so it uses the input system which may be a pain
Ahh that did it, thank you very much :)
Oh, okay, I didn't know that's how the freeze function worked. This is the code I'm using for the car's movement. I don't see where I'm rotating the car; truth be told, it's my first time using wheel colliders.
Hi everyone! I've been putting my mind to work with a bug but I really can't find the fix. When the player is below 45 FPS my character moves slightly diagonally. I've put a video down below and I'm holding only W or S and it's teleporting slightly to the right or to the left depends if I move forward or backwards. I'm using rigidbody for my player and I've avoided this problem a lot by trying to optimize the game better but some PC's are really slow and need to fix this for them. Anyone has any problem?
If you dont mind could you share the code for it?
The rigidbody and Input handling
well you're rotating it by steering
The roll is coming from centripetal force
It would come from your code
your movement looks overall jittery too
I was thinking this
First time i did not use rigidbody for my movement but switched to it by following a tutorial. I did not have this problem before. I was using CC then
one thing is:
_playerRigidbody.AddForce(transform.TransformVector(force), ForceMode.VelocityChange);```
Instead of doing this TransformVector thing, you can just use AddRelativeForce
Another thing:
float Mouse_X = _inputManager.Look.x * MouseSensitivity * Time.smoothDeltaTime;
You are inappropriately multiplying deltaTime into your mouse look
I was just about to say that
You're also calling MoveRotation in LateUpdate which is not correct:
_playerRigidbody.MoveRotation(_playerRigidbody.rotation * Quaternion.Euler(0, Mouse_X, 0 * Time.smoothDeltaTime));
I've been looking at the value of the steerAngle, and when I'm driving straight, it tells me 0. However, if I look at the object, the angle on the Z-axis is changing. Shouldn't it also go back to 0 or at least stop increasing?
So first, this would be in what I change it, right?
_playerRigidbody.AddRelativeForce(force, ForceMode.VelocityChange);
here just remove the smoothing for mouseX and Y, i guess
Yeah but also instead of:
_playerRigidbody.MoveRotation(_playerRigidbody.rotation * Quaternion.Euler(0, Mouse_X, 0 * Time.smoothDeltaTime));
I'd just say:
_playerRigidbody.rotation *= Quaternion.Euler(0, Mouse_X, 0);
MoveRotation queues up the rotation to happen in the physics update
if you get two Updates in a row before a physics update (happens all the time) you will miss a whole frame of mouse rotation
yeah, this looks better now that you say it
Hello, Ive been banging my head on the keyboard for a while trying to figure out how to make the camera follow the player properly on an spherical world. I dont quite understand quaternions so i dont really know how to do it. This is my camera manager script https://pastie.io/vuxtil.cs
obligatory: use cinemachine
I know with cinemachine i can just override World Up
but i dont want to bc i would like to have more flexibility
and i was having problems out of the box such as cameramachine stuttering when looking around
stuttering is probably going to happen with your camera controller too
with it just being newly installed
rotation = Vector3.zero; // (rotation is a Vector3; we're not messing with a Quaternion here
rotation.y = lookAngle;
This isn't going to work on a spherical world. You can't give any axis "special treatment" if "up" can be any direction
ah, you use it to set a local rotation, so maybe it'll behave
What is the problem?
that when i rotate around the world, it is as if the camera stayed on a flat layer, even though it is local coordinates
I thought of maybe adding the players rotation to the cameraManager, but idk how. this is how i have it set up:
so after doing the changes, the problem is still there. Even more the camera is a big laggy now on movement
There's a lot of stuff going on in your code so I'm not surprised if more tweaks are needed
If cameraPivot's parent isn't being rotated so that its up vector points away from the center of the world, then you won't get proper camera rotation
Try disabling your camera bobbing logic for the moment
can i just do transform.up = player rotation?
or player.up*
Yeah.. There are surely more changes to be done. The physics part always have been a scary and unknown part for me
Hey, I don't know where to post this question, so please redirect me to another channel if it applies:
For the Unity VideoPlayer component's Render Mode, what are the practical differences between RenderTexture and Material Override in terms of memory/resource gpu/cpu load? Also, Considering that I may have multiple video players (potentially playing at the same time, but not sure about this)
Thanks for any information!
sure, as long as the player is also properly rotated
Assuming that the camera pivot's parent is always oriented correctly, spinning cameraPivot around its local Y-axis should turn the camera left and right.
ooh, i thought that .up only existed when doing Vector3 xD Thank you!
okay
oh, it is. I mean that if you're copying the player's rotation (by mimicking the player's up vector), then just make sure the player's up vector is also right
You should inspect all of these things in the scene view. Make sure it's on "Local" mode (not "Global") in the top left corner
that will show you how each of your transforms is oriented
I fear it didnt fix it
In the function FollowTarget I added: transform.up = targetTransform.up;
still the camera doesnt rotate
you probably want to copy the entire rotation
just tried it and keeps happening the same
what is really strange is if I move in the direction i showed in the video, it has that behaviour with slightly teleporting left and right, but if I turn 90 degrees either left or right from that position and I move again W/S, it moves normal.
Also, the lower the framerate, the more I'm getting teleported diagonally when walking
Material Override will assign the internal video texture to a material property. Compared to API only, it's just one additional step, which is assigning the material property, which is not an expensive operation.
RenderTexture render mode performance depends on how exactly it works. It's possible that the VideoPlayer still has its own internal texture and it copies it to the target RenderTexture, which would be costly. It's also possible that when using the RenderTexture render mode, the VideoPlayer stops using its own internal texture and just decodes the video directly to the target RenderTexture, which would be cheap, as long as the target texture is the same dimensions as the source video.
if you disable camera bobbing does it reduce the jittering?
I.e. comment out CameraBobbing(inputDirection);
Yup
That got fixed
I think your problem is here:
Vector3 force = new Vector3(_currentVelocity.x - _playerRigidbody.velocity.x, 0, _currentVelocity.y - _playerRigidbody.velocity.z);
_playerRigidbody.AddForce(transform.TransformVector(force), ForceMode.VelocityChange);```
_currentVelocity.x - _playerRigidbody.velocity.x specifically these arithmetic operations
_currentVelocity is ostensibly a local space velocity vector
Whereas _playerRigidbody.velocity is a world space vector
you are mixing two coordinate spaces
which is no good
The right way to do this would be:
Vector3 desiredWorldSpaceVelocity = _playerRigidbody.rotation * new Vector3(_currentVelocity.x, 0, _currentVelocity.y);
Vector3 diff = desiredWorldSpaceVelocity - _playerRigidbody.velocity;
_playerRigidbody.AddForce(diff, ForceMode.VelocityChange);
But really that's just a more complicated way to write this:
Vector3 desiredWorldSpaceVelocity = _playerRigidbody.rotation * new Vector3(_currentVelocity.x, 0, _currentVelocity.y);
_playerRigidbody.velocity = desiredWorldSpaceVelocity;```
Thanks! So if I had multiple video players with different videos to play set to Material Override, each would need their own material if I wanted to play them simultaneously - or at least if I pause one while the other plays and still see each video's paused frame displayed.
It seems I have the option to use the same material for all video players, or each with a unique material depending on how I would handle the case where two show in the screen at the same time? (and I guess the same is true a RenderTexture?)
i'll give it a shot now, thank you!
GOD DAYUM it worked
- Yes
- If you use the same material for all video players, whichever gets initialized last will overwrite every other player. For managing multiple players, you might find it easier to use the API Only render mode and write a manager script that assigns the active
VideoPlayer.textureto the screen material.
Thank you so much! It has always been in the fog with all the physics and you helped me! Thank you again! ❤️
I've also enabled the camerabobbing and lowered down the sens, it's not laggy anymore. The problem is that it feels like the up-down res is different from the left-right one
Which should make sense since one rotates the camera and one the rigidbody
hi does someone know how to 'lerp' the reverb filter effect on an audio source?
Aren't those effects part of the audio mixer, not the source?
I mean yea it's not an effect directly on the audio source
I'm talking about the reverb filter component
Ok then first place I'd look is the documentation for that component
Looks like it has a bunch of different properties you could theoretically "lerp"
i already did
yea that's what im doing now, going to lerp each value from the off preset to whatever other preset
but I hoped I was missing some easier way to do that
this is very weird, for some reason I can't dash in a certain direction
Vertical = Input.GetAxisRaw("Vertical");
LR = Input.GetAxisRaw("Horizontal");
if(DashCool >= 0.8f){
if(Input.GetKeyDown(KeyCode.Z) || Input.GetKeyDown(KeyCode.Space)){
//Kick!
body.mass = 1;
body.velocity = new Vector2(LR, Vertical)*20;
DashCool = 0;
}
}
if I try to dash to the left and up it doesn't do anything
any ideas?
not that I know of
ah okay thank you anyway
So that would be which keys all at once?
W, A, Z?
This might be a hardware issue with your keyboard.
Try pressing all those at once with a tester like this:
https://www.mechanical-keyboard.org/key-rollover-test/
are you intentionally using a vec2 instead of vec3?
its a 2d game
but I can try with a vec3
Vec3 won't change anything
body.velocity is a Vector2 if it's RB2D
wait tf it isn't picking up the space key at the same time as the other 2
there's no context in his message that says its 2d
other than the V2
exactly
but the symptoms would have been different
that's why i asked
how can I fix it???
can I fix it???
am I consigned to eternally being unable to go up and to the left???
You... use a different keyboard 🤣
or change the controls
wrong one
thats annoying
come to think of it I did notice this in some other games I was playing
I can do space and WA but not space and Uparr Leftarr
its the one that came with my laptop
Is it a cheap laptop? 😉
Nah pretty much every keyboard has n-key rollover limitations
it's just a matter of which key interactions do and don't work for your particular keyboard
There's not really a way around this problem in general (you can't control your player's hardware), other than allowing key rebinding in your game
I feel like up, left, and space are pretty common ones
how did lenovo not check
They probably didn't design this as a gaming computer
unless they did
in which case, shame
ugh
im going to do what the above video did
why couldn't they have made it like backslash and forward slash or something
@leaden ice do you have any idea on the code you gave me, when I go down or up on a ramp, i walk hard on the way up and float slowly in the air when I go down . What could I change to make the gravity be normal
Tried tweaking settings in the rigidbody but no use
Yeah it's because our code sets y velocity to 0
Set it to whatever RB.velocity.y was already
Thank you again! ❤️
hey thank you!
I'm not sure what this is called at its core, so I didn't look anything up but, I wanted to pull off this magic in my own script and was wondering if it could be done without pulling too much of a hassle, otherwise I'll just switch to plan B. Any ideas?
What would behave kinda opposite to Lerp?
Lerp starts fast but slows down, what if I want to start slow but accelerate exponentially but also towards a value, like Lerp?
it's a UnityEvent
thank you box!
lerp shouldn't be starting fast and slowing down, it should move at a consistent rate unless you are lerping incorrectly. but you could use something like an animation curve to determine the t value for your lerp to provide the desired easing
You are likely doing A = lerp(A,B, T) which means A is constantly changing to be closer to B. A is supposed to be the starting value, not the current value.
hey guys so for some reason i cant call CollectCoin(); in my player script anyone can help?
Because CollectCoin is in a different script
yea but its public
You would have to reference the PortalManager and access the method through that
Completely irrelevant
how can i do that tho
Look at the link I sent 🤷♂️
Once you have a reference, you do this:
myPortalManagerReference.CollectCoin()
With myPortalManagerReference obviously being a made up name for a variable
the application.quit() command doesnt work for me, kinda.
i made 2 apps and 1 game, the 2 programs that i put in microsoft store as type MSIX or PWA app, and the game as type Game. in the 2 programs the application.quit() command works but in the game it doesnt. why ?
Which PortalManager do you want to call CollectCoin on
Hi, I am working on a spline generator with procedural meshes, I have gotten the individual segments working and I am focussing on adding the last part of being able to expand on the amount of segments, so I can have longer/multiple splines. I am having a (probably easy to fix) bug where my vertices dont update to include both segments when rendering the mesh at the end of the math. Right now I have it setup so that it does what is shown in the screenshots but I am trying to have them both combined into one continous spline. I have an inkling through debugging that it revolves around how my lists are setup and updated but, I can't pinpoint anything.
ok so it worked but for some reason it aint activating and taking me to the next lvl
so idk what to do
Try putting a debug.log to see if it even runs
What part of your code is supposed to load a new level? Tbh this definitely should be in the beginner channel
these are my codes
it was working perfectly fine b4 i added the portal manager script
its basically when i collect a coin the portal appears and is accesible
I am trying to rotate a map markers Z-axis by a players Y-axis.
Marker.transform.eulerAngles = new Vector3(0, 0, Player.transform.eulerAngles.y);
This works well until the X-axis of the player rotates more than 180deg, flipping the Y-axis by 180deg (or whatever quat shenanigans happens).
How'd one rectify something like this?
Just realized you'd actually be looking behind you at some rotation.. Please disregard 🫢
Stop reading euler angles from objects and trying to do logic based on them
https://learn.unity.com/tutorial/displaying-score-and-text?uv=2022.3&projectId=5f158f1bedbc2a0020e51f0d#650b5addedbc2a3242890dd4 based on this tutorial for the script for player controller i follwed it step up step and for some reason the ball doesn't move but the rest object moves, so can someone help me with it?
you'll want to do something like:
Vector3 playerForward = Player.transform.forward;
Vector3 projected = Vector3.ProjectOnPlane(playerForward, Vector3.up).normalized;
Vector3 rotated = Quaternion.Euler(90, 0, 0) * projected;
Marker.transform.rotation = Quaternion.LookRotation(Vector3.forward, rotated);
This code in the screenshot is throwing an error:
ObjectDisposedException: SerializedProperty itemsDisplayed.Array.data[1].inventorySlot.item has disappeared!
ObjectDisposedException: SerializedProperty itemsDisplayed.Array.data[1].inventoryEntryObject has disappeared
I looked up the error, but it didn't come up with anything related to using RemoveAt, so I'm not sure what's happening.
Doesn't RemoveAt normally handle this on its own?
When and where are you running this code?
That's an error with the serializer
does anyone know the roll a balll tutorial
anyway this code seems like it wouldn't work anyway. As soon as you remove one of the elements all the other indices could/would be wrong
you're doing a reverse iteration but only over the indices list, not over the actual itemsDisplayed list
I guess it could work if the indices are guaranteed to be sorted
I'm running it on a button click, when I am removing an inventory slot at Line 256 Here:
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.
I HAVE to iterate over the list backwards, iif I don't, the indexes get fucked up, don't they?
Because when I remove 1, then the entry at 2 slidess down to index one, midloop?
yes but you're iterating backwards over the index list, not the actual itemsDisplayed list.
if the indices aren't in order you could be removing in any order which will indeed fuck things up
The indexes are in order, or so I thought. The index list is added in ascendding order, as seen here:
//For each item in the inventory, add the index of entries with no items left into a list of index numbers.
for(int i = 0; i < Container.Count; i++)
{
if (Container[i].amount <= 0)
{
_removedIndexes.Add(i);
}
}
How am I supposed to provide a function with a list oof indexes to remove, when reemoving one index changes the index of all other entries on the list,, if not by iterating backwards?
No you're good
It just wasn't clear that the indices were in order
the function makes no mention of it so it could have been happening in any order afaik
Yeah, the indexes are in order, which is why I'm not sure what is going on here.
anyway this error is more likely related to the Destroy call than the RemoveAt
What should I use in place of it? I'm trying to delete unused inventory slot GameObjects.
Well it's not a problem per se - it just seems like somehow you're doing this during the serialization process or something? Basically I would expect this error if and only if you were writing editor code somewhere
e.g. a custom inspector
or custom property drawer
do you have any of that?
I do see this... using UnityEditor;
I guess for CreateAssetMenu?
I do have two of those. Let me grab them.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(InventoryObject))]
public class ScriptableInventoryObjectEditor : Editor
{
//This program alters the Unity Editor, adding a refresh button to the Inventory Scriptable Objects for Debug Purposes.
//Add Future Inventory Editor stuff here!
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var script = (InventoryObject)target;
if (GUILayout.Button("Refresh Debug", GUILayout.Height(40)))
{
script.DebugRefresh();
Debug.Log("Attempted to Refresh");
}
}
}
Is there some sort of thing I should add here to handle it, or is this not where the issue is cropping up?
Ah
I think it's probably this script.DebugRefresh thing
nvm though that should only happen if you press that button right?
are you pressing that button?
No, never. It's only used outside of runtime, to refresh a debug inventory.
Let me get a pastebin made. Might shed some light on it
I think I might have figured it out, or at least noticed something wrong.
This code is ran when I hit a button in the editor outside of runtime too, could it be possible that this is interfering with some other DatabaseRefresh method?/
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.
InvalidOperationException: The operation is not possible when moved past all properties (Next returned false)
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <88872b21b1e746a7ad699974a2be8304>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <88872b21b1e746a7ad699974a2be8304>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <88872b21b1e746a7ad699974a2be8304>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <88872b21b1e746a7ad699974a2be8304>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <6350d5f72ec34638985fbaab06c4c559>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <6350d5f72ec34638985fbaab06c4c559>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <6350d5f72ec34638985fbaab06c4c559>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <6350d5f72ec34638985fbaab06c4c559>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <68890c016c7a40d7ab0d5ba9aecf643f>:0)
I'm getting a different error now.
I mean it's definitely an editor UI issue
does it still happen if you unselect whatever object you have selected
(i.e. close the inspector)
ok so it's related to your inspector somehow
if you comment out your custom editor does it also go away?
I'll try it with each. I have two, one that modifies a Debug Inventory ScriptableObject, and one that modifies a Database Scriptable Object.
is the SO not being saved properly?
Yes, if I remove both of my custom editors, it no longer seemss to throw errors. How do I make my custom editors deactivate on runtime or something?
The issue SEEMS to solely be because of the custom editors adding buttons to my Scriptable Object for the Database and Inventories.
Hello, I have a bug, where when I change the scene, an image of the last scene stays as background of my game, it does not appear in the inspector, but it looks wierd, and even in build I can see that issue, has anyone gotten the same problem? I change the scene using a button, which has the next code:
{
Time.timeScale = 1;
SceneManager.LoadScene(scene, LoadSceneMode.Single);
}```
FirstScene:
Second Scene:
And they ONLY occur when I destroy certain gameobjects while certain other gameobjects are selected during runtime
Its like it being rendered on top
What does the scene look like when you open it from the editor?
It works fine, it just looks like that when I open it from the button "Play"
Oh no, wait, It looks still with the bug
Even when The game is not playing
I was reviewing some stuff and I found out that if I turn on and off a camera it returns back to normal,
I have 2 cameras
The gameplay one (main camera)
And a Camera for UI, I have two, because I wanted to render particles on top of UI, And I followed a tutorial which told me to have 2 cameras, and do camera stacking
This is the camera that gave me problems
I´m thinking, mybe if I change the culling mask will it wokr?
Let me try it
Nope, I still have the same problem
well, I added a script which deactivates and then activates that camera whenever you open that level and I fixed it, but it just like a workaround, I still don´t know why that camera contains a render of my previous scene
this is just an overlay camera so the base camera is likely related?
heya, is anyone familiar with a way to get rid of vertical sloping in marching cubes? I'd like to preserve horizontal sloping simultaneously
This is my main camera:
Is this related to code? If not, you'll get more responses in #💻┃unity-talk
To move the message without cross-posting, delete the messages here and repost there.
k thx
You could use triplanar mapping
which kind of side-steps the entire problem by not having UVs at all
my issue is that these slopes will still exist in the geometry and i’m trying to get perfectly flat walls so i can map some textures to the sides
the smeared textures are just a placeholder atm
Oh, the vertical sloping in the actual geometry
I'm not clear what the difference between vertical and horizontal sloping is
yeah same
in terms of the point of it, i’m trying to achieve a pixel art look
so the top has to be flat and the walls have to be flat as well, but the horizontal slopes are fine
basically from a top down perspective it can be any polygonal shape, but from a side on perspective it has to be square
Vector3 edgeStart = position + MarchingTable.Edges[triTableValue, 0];
Vector3 edgeEnd = position + MarchingTable.Edges[triTableValue, 1];
//Vector3 vertex = (edgeStart + edgeEnd) / 2;
Vector3 vertex = Vector3.Min(edgeStart, edgeEnd);
vertices.Add(vertex);
triangles.Add(vertices.Count - 1);
edgeIndex++;
changing from the commented vertex = line to the uncommented one allows exactly half of the mesh to look correct
ah, okay, so every face must be either aligned with the Y axis or perpendicular to it
I haven't done marching cubes before so I haven't gone any immediate thoughts..
given min/max can achieve either half of what i'm looking for, i feel like there's a really simple line that would do it that i'm just missing
this might help illustrate the issue with the slopes
if you just want it to stop being affected by gravity set it to kinematic and set velocity to 0
never make an object static in runtime
if you want to loose the whole rb2d functionality you can always disable components with [...].enabled = false
Oh I wasnt aware that it is not available for rb2d
Either way just Setting simulated to false should disable it completely, setting it to kinematic removes it being affected by most of physics
is there suppose to be a new system that replaces the event system? Specifically I'm looking for the equivalent of EventSystem.current.RaycastAll in the docs.
No. It was probably moved to the dedicated unity ui package documentation.
int _overdraw = RemoveSlottedItem(_amount, _fromslot, out _excess, true);
I don't think I understand how the "out" keyword works. I know this function is setting _excess to 0, but _overdraw is getting set to 5. How do I make RemoveSlottedItem output the _excess variable being set inside of it?
Nevermind, I figured it out, I think.
Out is just like an extra return value, basically.
Just in case that helps.
It won't affect the thing to the left of the equals, just gives you a local variable you can use
Yeah, it's basically setting the _excess variable when it's run, and initializing it, right?
It's equivilent of saying like, "_excess = (insert the code in the function)"?
well, somewhere inside the function, you would write _excess = (whatever)
And then yeah, wherever you call the method, you could use that _excess with whatever value is passed into it inside the method
Yeah, I thought it was like an extra return, which you had to access as if you were running afunction with a return, to initialize a differnt variable
Now I get it. And now, my Inventory system is 100% complete and 100% functional!
It has:
1. Modular Stacks (There are as many inventory slots as there are discrete stacks of items
2. The ability to Add items generically to the inventory in any chosen amount (and have them stack with available slots)
3. The ability to Add items to specific slots in specific amounts (and have them stack if the same item is in that slot)
4. The ability to generically remove a specific item from any valid slot in the inventory
5. The ability to remove an unspecified item from a specific slot.
5. The ability to remove a specific item from a specific slot, and fail if it isn't there.
6. The ability to take an amount of items from one slot, and move them to another, stacking if there are items in that slot
With error checking, an override to force removal even if the amount being removed exceeds the amount in the slot, a return that tells you the excess removal left over if you do that, for feeding into other functions, and all that jazz.
Is there anything I'm missing, for making a robust and omnipotent inventory system?
So, Google seems to imply that the answer is "no" and that this has been an issue in Unity for the past ~ever, but but does anyone have a way to detect whether the caps lock key is on?
You can solve this as following: using System.Runtime.InteropServices; [DllImport("user32.dll")] public static extern short GetKeyState(int keyCode); bool isCapsLockOn = false; void Start() { isCapsLockOn = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;//init stat } void Update() { if(Input.GetKeyDown(KeyCode.CapsLock)) { is...
@eager pewter thats windows only btw, if you're doing macos:
[DllImport("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices")]
public static extern long CGEventSourceFlagsState(int keyCode);
void Start()
{
bool CapsLock = (CGEventSourceFlagsState(1) & 0x00010000) != 0;
Debug.Log(CapsLock);
}```
Nothing platform agnostic, eh?
sadly not for a state of a key without a keypress event
you can add both and just use this https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
This is going to sound wierd and pointless/unoptimal/bad practice... but humor me for the time being. Would I be able to check the platform and do this at runtime?
wdym do at runtime? how else would you do it
you meaning checking platform?
cause it will compile with both since its string value for dll, but once you call the method on wrong platorm you get dll not found
makes more sense not including a windows only library/function in final code if you do say macos
Working Unity-adjacent, not necessarily in Unity. I think I've given a good explination in the past, lemme find an example rq.
Or not apparantly
Essentially, I'm working on a mod for a Unity game (not online competitive, there's nothing against game TOS I'm doing, etc. All within the rules). I'm packaging up a .dll file which is injected into the game at runtime via BepInEx. So everything I do needs to be in scripting (not editor) and at runtime. I don't know what platform people will be running my mod on, so within the code, after compilation, I'd need to check the platform and go from there.
Which is why I was hoping for a neat little "is caps lock on" option built into Unity
This does seem helpful though: https://docs.unity3d.com/ScriptReference/Application-platform.html
thats only for checking the platform, knowing if the caps lock is on without keypress can't be done inside unity.
Also there is no discussing of modding on this server so you're pretty much on your own from here . Community rules #📖┃code-of-conduct
shoot i did not see that my bad
Out of curiosity, where'd you find this?
found it on stackoverflow ofc
Guys what is better Unity or Godot for 3 D Games
depends what you're making
they're just tools
pick whatever feels comfortable for you
Yeah but unity is more polished that Godot but Godot has a better feel than Unity
So I'm not suree
Like it more comfortable while when I snooped around unity it felt more complex
yeah must be preference then because i found unity dumb easy in comparison to previous tools I've used
also the c# documentation is kinda meh for godot , too much focused on their gdscript
I think I'ma do godot
btw this is a code channel, general unity questions go in #💻┃unity-talk
can someone explain the reason why interfaces are used here instead of abstract classes? https://gdl.space/eyoyuwawil.cs
this is the repo in question https://github.com/Unity3D-Projects/UnityGameplayAbilitySystem/blob/master/Assets/Plugins/GameplayAbilitySystem/Interfaces/IAbilityTags.cs
or the reason for using either in general in this case? it seems like it serves no point as only one other class uses the interface
interfaces can be substituted for abstraction
more of a preference if anything, but both still cant be serialized on the editor anyway
Hi. I had this issue(first image)
So I Fixed it with a script temporarily:
public class SomeTest : MonoBehaviour
{
public void FootL(float theValue)
{
Debug.Log("PrintFloat is called with a value of " + theValue);
}
}```
And it stopped displaying NULL error.
But can't find the original code in the animation asset im using. I thought their method would also be called "FootL" since their animations are calling an event with such a name?
But I dont see anything (last image):
(Im trying to copy their animation event code but i cant find it, and the name seems to be different somehow, or idk)
Only the person who programmed this can tell you exactly why they used interfaces.
The interfaces you linked do not provide any implementation, so they "make sense" as interfaces rather than an abstract class, from a theoretical pov.
In general, C# does not allow multi inheritance, but it does allow implementing multiple interfaces, so sticking to interfaces often boxes you in less in how you can use them
Nvm I found the code
I think my VSC just breaks
It can find it now after i entered the script
but it couldnt before
true, but it just doesn't make sense why for example, "GameplayEffectTags" which uses the interface "IGameplayEffectTags" is the only thing that implements it
I assume they did that so it's easier to build your own thing on top of it, i.e. implement your own IGameplayEffectTags if you wanted
ah i see
so on it's own, theres no point at all, they could just be defined without the interface
there's an argument of implementing variance later on, which would require these indentical interface implementations
yeah, that makes sense. I just was confused as the only reason to use interfaces is if you were having atleast 2 things implement it
it just seems a bit odd since the class GameplayEffectTags is already generic and making something else inherit from that interface wouldn't make much sense
I'm using visual studio code, and when i try to use things like the OnTriggerEnter2D function, the intellisense doesn't work. Do i have to add it manually? Is there anything I can do? Or should i just use visual studio.
is using Transform.Find() a bad habit? as it's basically hard coding and prone to failure if mistyped?
yes, and for that reason among others
so really assigning the inspector is better
much better
and if it's a reference created at runtime, you've got singletons for quicker access instead of having to search the scene
Almost every one of the gameobject/transform Find functions are noob traps. At best, they still search through large amounts of the hierarchy for a reference that can usually be passed more cleanly.
like, imagine sifting through 10,000 objects, looking for a specific object by name/tag/etc?
as opposed to just having the reference
And for reference, GetComponent is fine
Hello everyone! I'm currently working on developing a visual asset for Unity aimed at managing JSONs in a more intuitive manner. But i've found a little problem...
I'm seeking an efficient method to handle custom data types within my asset. Specifically, I want to enable users to seamlessly add their own data types. For instance, consider a scenario where a user wishes to introduce a data type named 'WeaponType' with various values such as 'Rifle', 'Pistol', 'Shotgun', and so forth.
My aim is to ensure that my asset remains flexible enough for users to define and utilize their custom data types visually. However, the complexity lies in these data being of a custom type, not simply float, char, int, or string.
Given this context, any ideas?
Use the TNRD serializable interface plugin. Make an interface for your plugin to use like ISaveData which you can serialize.
That is my idea
ohh, nice :>
thankss!
how do i change the samples it doesnt say samples where it should
public void OnClick(InputAction.CallbackContext context)
{
if(!context.started) return;
var rayHit = Physics2D.GetRayIntersection(_maincamera.ScreenPointToRay(Mouse.current.position.ReadValue()));
if (!rayHit.collider) return;
Debug.Log(rayHit.collider.gameObject.name);
if(context.canceled)
{
Debug.Log("mouse released");
}
}
So I try to make project print that the mouse was released, but so far i can only get the click event to work for press part only. How to resolve?
You'd have to show how you connected this function to the input action
If you only subscribed to performed you need to subscribe to canceled as well
It's hidden in the ... Menu top right
Not what I asked for
You somehow hooked this up to your code
That's what I want to see
Either through PlayerInput or manually subscribing to an event or something
Ok that should just work actually
Oh it's your code
Look at the first line in your function!
You're returning immediately @dark kindle
thank very much , cant believe i mised that
I got it to work by putting before !context.started
but maybe it better practice if I have separate function like eg onRelease
and that only handles the event when mouse is released
or just a switch statement
or better branching logic
switch (context.phase) {
case InputActionPhase.started:
//
case InputActionPhase.performed:
//
case InputActionPhase.canceled:
//
}```
enums and switch statements go together like PB&J
i would go as far as to say >90% of switch statements should be a switch on an enum type
what is better practice between public static GameManager Instance { get; private set; } and private static GameManager instance; public static GameManager Instance
if you don't need any custom logic it's fine to use the autoproperty. Once you need custom logic you need to switch to a manually defined property. They are otherwise identical for all intents and purposes.
guys i am working on adding audio for my player and other objects but i am getting the error for set can anyone please help me
- have some patience next time. i was about to answer you in the beginner channel before you deleted the question
- do exactly what the error suggests, when adding an access modifier to either the getter or setter for a property it must be more restricted than the property's access modifier. so either remove the private from the setter or make the property public if you want it to be publicly gettable but privately settable
i didn't know that you'd get an error from applying an equally restrictive modifier, interesting
I am sorry for deleting it it was for biginner and i didn't see it
I have made it private so that changes for audio can only be made in this but this error is not making any sense i am following a tutorial that guy wrote the exact same thing and didn't get any error
your property is private, therefore the setter is already private by default. you probably want the property to be public like i suggested at the end of my message
please actually read the messages you see
also, the tutorial did not write the exact same thing, because then it would've been a compile error
i am sorry why are you being rude?
okay
unless the tutorial literally just doesn't work, of course, which is always a possibility
my dude, the error message told you what was wrong. i also told you exactly what to do and now you're asking again what you need to do to fix it
Sorry
do you not understand what an "access modifier" is?
i do
what is unclear about the error message, then?
Let’s say I have a bool and an enum, and I want to make a switch state on the combination. Is there a cleaner way than:
switch (enum) {
case 1: if bool
else
case 2: if bool
else…
bitmask
that sounds like it would not help my code be cleaner :/
Cases can be chained as long as they don't have any instructions in them, so you can do something like:
switch (thing)
{
case 1:
case 2:
// common implementation for cases 1 and 2
break;
}```
Execution "falls through" case 1 to case 2
i am not looking for fall through. I am looking more for something like:
switch ((enum,bool) {
case (1,true): …
case (1,false): …
case (2, true):…
That works
I thought you couldnt do fallthrough in c#
like a clean switch on a value tuple
you can do fallthrough
it’s just a bit more limitted
other languages let you basically do
case 1: do x;
case 2: do y; break;
wheras C# tells you to GFY
but you can do
case 1:
case 2: do X; break;
what would be the right syntax to do that switch on a value tuple?
switch ((a, b))
{
case (1, true):
break;
}
ty. just what I was looking for
And if you want a case where one of the two values of the tuple doesn't matter, then you can use a discard in the tuple: case (4, _): (a is equal to 4, and b is whatever)
{
this.shape = shape;
this.mesh = mesh;
this.resolution = resolution;
this.localUp = localUp;
axisA = new Vector3(localUp.y, localUp.z, localUp.x);
axisB = Vector3.Cross(localUp, axisA);
}
public void ConstructMesh()
{
Vector3[] vert = new Vector3[resolution * resolution];
int[] tris = new int[(resolution-1) * (resolution - 1) * 6];
int trisInx = 0;
for (int y = 0; y < resolution; y++)
{
for (int x = 0; x < resolution; x++)
{
int i = x + y * resolution;
Vector2 percent = new Vector2(x, y) / (resolution - 1);
Vector3 pointOnUnitCube = localUp + (percent.x - 0.5f) * 2 * axisA + (percent.y - 0.5f) * 2 * axisB;
Vector3 pointOnUnitSphere = pointOnUnitCube.normalized;
vert[i] = shape.CalculatePointOnPlanet(pointOnUnitSphere);
if(x != resolution - 1 && y != resolution - 1)
{
tris[trisInx] = i;
tris[trisInx +1] = i+resolution+1;
tris[trisInx +2] = i+resolution;
tris[trisInx +3] = i;
tris[trisInx + 4] = i + 1;
tris[trisInx + 5] = i + resolution +1;
trisInx += 6;
}
}
}
mesh.Clear();
mesh.vertices = vert;
mesh.triangles = tris;
mesh.RecalculateNormals();
}```
how do i make the local "green" direction arrow on the way the planet piece is facing? (i need it for using navmesh pathfinding)
set transform.down to a vector pointing toweards the center of the sphere
the green arrow (Y) will now point out of the surface, and the red and blue arrows (X and Z) will be tangential
although, that would wind up rotating the entire mesh
why is that error appearing?
Perhaps you have another instance of the component that's missing the reference
or something is setting the field to null at runtime
How would you go about making a modifier system in a 2D game? By modifier system i mean items (like in binding of isaac or any other roguelike). For example making the gun shoot 2 projectiles in 2 directions, making the projectiles ricochet, changing player/enemy speeds etc.
composition
This is a really broad topic.
I've poked at it a few times, but I haven't really made a game that's "all in" on stacking modifiers yet
Composition is definitely the way to go.
isaac has a lot of edge cases so I expect a lot is composite
Okay, cheers, ill have a look at it. First time im hearing the word xd
basically,
if(chain)
if(fork)
if(bounce)
I want to glue 2 gameobject I just want them to stick together no rotating no sliding no nothing, like they are snapping together like lego, all the joints I tried just had the object rotate and slide slightly
2d physics
and a FixedJoint2D didn't do what you wanted?
no it isnt stiff enough, I just made the joint and connected the rigidbody no other additions
apparently it'll work better if you put the joint on the heavier object, so check that if the two rigidbodies have different masses
Here is a photo, I created the fixed joint when the blue object collided with the yellow, when they collided the yellow was right above it then it start moving around by itself even blue is stationary
they both have the same "mass"
blue is the player
rather than wandering off in different directions
yellow is a glue thats stick to it on collision
oh, just yellow is moving; blue is stationary
The colliders are overlapping, which could be causing weird physics problems
hmm, how can I fix it?
why not just compile the dll directly into your project?
Try turning off the collider on the yellow object and seeing if it stops wiggling around
I'm not sure what the easiest fix would be, though
no it still drifts to either the left or right whether or no the box collider is on
I just want the blocks to stick together like a grid with the player as the center
I cant just set there position to be (x,y) from player so they dont clip through walls
I don't know exactly where to ask this question so Ill ask here. How do I change the camera used as the scene camera? I am using the universal rendering pipeline to dynamically hide/reveal objects. This works almost too well as it hides objects from me even when I am in the scene camera. I set the custom render pipeline to be the default so all of the regular cams used it, but I don't want the scene camera to use it. I see where to change some of the settings(Fov, easing, draw mode, toggles) but I don't see how to change the rendering pipeline used.
How are you "using URP to hide/reveal objects" exactly?
The details are important
I don't draw the objects I hide, I save the mask to the stencil, then I redraw the hidden objects. I don't want the scene camera to do the hiding part
How? In code? Show the code?
Typically you can say like if(Camera.current == SceneView.camera) return; or something along those lines
its the same setup as this tutorial: https://www.youtube.com/watch?v=CSeUMTaNFYk&t=1174s
But there is no code, only the following rendering object
The layer "Mask" contains objects rendered where the player can see and the other layer in the "see through" pass includes the other objects
i have a problem with DLLs. Never worked with it before. I try to use SDK from real sensors (camera). The provided SDK is .NET. So i created plugin, how the unity says, but when i import built dll to Unity. Unity says this error. Code is just init the Library. 😦 doesnt anyone know?
When i dont init the library, everything is ok. Text shows in console.
isnt there anything else to try? to get input data from cameras? :/
as it says, have you added ic4dotnet.dll to your project too?
im trying to make a grab system how would i move the object to a empty gameobject i also want it to all be physics based
oh it has too? >.< wait i will try, ty!
private void RotatePlayer(PlayerController controller)
{
if (Input.GetKey(KeyCode.W))
{
controller.currentXTargetRotation -= Time.deltaTime * controller.turnSpeed;
controller.hipsCJ.targetRotation = Quaternion.Euler(controller.currentXTargetRotation, controller.currentYTargetRotation, controller.currentZTargetRotation);
}
else if (Input.GetKey(KeyCode.S))
{
controller.currentXTargetRotation += Time.deltaTime * controller.turnSpeed;
controller.hipsCJ.targetRotation = Quaternion.Euler(controller.currentXTargetRotation, controller.currentYTargetRotation, controller.currentZTargetRotation);
}
}```
Hey everyone, Im trying to make the player do a flip using its target rotation on configurable joint, it works, but only in the world space forward, if i turn around, it tries to flip the original direction it was in. Any ideas? Thanks
oh, it sopped to show! ty. But now it has problem with the library >.<, but its progress! i happy! 
FWIW if you just need to use ic4dotnet.dll in your unity code, you usually don't need to write your own separate DLL too, you can just put the third-party dll into the project and use it directly
Does onTriggerEnter not work when using a Character Controller?
I have this simple code in an empty gameobject with a collider marked as isTrigger
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class finishLevel : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void onTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player finished");
}
}
}
But it never seems to register the player
onTriggerEnter -> OnTriggerEnter
Thank you so much, I feel like a complete idiot, I couldn't see that for so long
I'm used to Java code always starting a method name with lower case
i have a question, im using the httpclient to get the data of the player from the database, but in the universal windows platform build that i uploaded on the microsoft store the httpclient commands dont work.
why ? can anyone help
we're very formal here in C# land, we capitalize everything 😄
it's been a while since i touched UWP but if i remember right it uses a more limited version of the .NET framework there? you could try switching to IL2CPP, otherwise i guess you're going to have to get something third party or use UnityWebRequest
if (Holding)
{
TargetDirection = TargetPoint.position - Grabbed.position;
Grabbed.transform.GetComponent<Rigidbody>().AddForce(TargetDirection * 2f, ForceMode.Acceleration);
}
How do I get the grabbed object to get exactly to the target point.
hmm isnt the scripting backend for uwp already IL2CPP ?
idk, what's it set to in your build? if it's not available on either backend then it's probably just not supported
the scripting backend in uwp is set to IL2CPP and i cant change it
i can change it in normal windows platform
by "don't work" do you mean it doesn't compile or you get an error?
because its not in the unity editor i cant see the error exactly, and i set it to only show a network error panel if the error is a webexception like this:
catch (Exception e)
{
if (e.InnerException.GetType() == typeof(WebException))
{
//errorMessage.text = "Network Error, Check your Internet Connection";
errorMessagePanel2.SetActive(true);
}
else
{
Debug.LogException(e);
}
}
so i dont exactly know
oh you mean compiling as in make the build ?
well, probably time to change that logic and see if it throws a different error 😛
so what if you get a HTTP error?
normally at the start of the game the user signs in to get his points and progression, but if it doesnt work he cant start from where he finished the last session
on a lot of platforms you need to add permissions for HTTP requests/internet access in the manifest or platform settings, might be worth checking that out
is it this ?
no, that's just to stop it requiring HTTPS
the bit i linked is the capabilities section
oh this ?
that's what i linked yup
umm do you know which one exactly i have to tick? there are a llot 😅
Oh. Oki. I will try it!
How could I interact with world space canvases while cursor.lockstate = locked?
Isn't it supposed to work normaly except the cursor is locked into the centre of the screen?
you mean like this ?
Yup
Sweet! Imma give it a try
It shows up the cursor, but nothing Cursor.visible = false cannot solve, Thank you very much!
yeah had the same issue, had to force the cursor visible = false myself
i would guess InternetClient at least
Ok, thanks a lot for the help man
hope it works, like i said it's been a long time since i touched UWP 😅
im getting this error :/ I put the DLL into assets/Plugins folder. When i call any function, it gives me this error. Dont you knwo where can be problem? :/
you need to copy the native dlls used by ic4dotnet into your project too
looking at the nuget package, there's 4 native dlls
oh! it works! ty!
still cant find the cameras, but no errors 
glad to hear it! good luck with the rest
Any way of creating a UML/Class diagram with Visual Studio with an entire Unity project?
you know, I was just looking into that earlier
but I didn't go very far
I was more interested in figuring out a dependency graph
Visual Studio has the Class Designer, which may do what you want
How would i add a keyframe to a material via script?
keyframe to a material ?
wdym
you can animate material properties
I'm a little unclear about "adding a keyframe" via script, though
is this an editor script?
I haven't done that from code before myself
but I can't imagine it's any different than keyframing anything else
something like this
where i move this gizmo and it will apply the animation the material shader vector
can someone help, im trying to change my Scripting Runtime Version to .NET 4.x but i dont have it
please tell me no one paid $50,000 for this

Say I have a script (UIController) and a different script that inherits from it (MainMenu : UIController) and I have a serialized field within UIController that I do NOT want to appear in the inspector for Main Menu. Is there a way to make that happen?
I think I need to mark the field as private, serialize it, and then use a local accessor method... bleh
You can hide the field in the inspector, but this will also hide it in the UIController
The only other option that comes to mind is a custom editor
this is what I get for trying this new thing called "don't put all of your UI code in one gigantic class without organization"
hmmm nope even while private it's still in everything that inherits from UIController. I should have seen that coming tbh
I'm trying to make a 2D light ray simulation that involves game objects that act as light sources and send out raycasts to determine how the light ray would travel around the scene. The rays can be redirected by mirrors and other factors, so some rays are made of more than one line segment. I am currently debating on the best way to draw the "light rays." So far I have tried using the LineRenderer and TrailRenderer components, but the problem arises when I need to draw more than one light ray per frame (I am hoping for at least several hundred). In order to start a new ray, I need to backtrack from the end of the previous one along every vertex in the ray all the way to the source and then start drawing the new line from there because the LineRenderer only draws one continuous line. From my research, it appears that the LineRenderer or a procedural mesh with MeshTopology.Lines set are the most common ways of approaching this. Is there a more proper/better way of approaching this?
I made this function to save stuff and it works fine the first time I'm calling it.
https://pastebin.com/tVg0ambN
However, when trying to save a second time later on, I get this error:
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.
Again, the first time it works exactly as it should. But calling the SaveWorld function again later on, in another script, gives me the error.
I bet you're leaving the file open.
yeah, you're leaving the file open
oh, no, you've got using right there...
Perhaps you aren't correctly using running SaveWorldAsync?
When you run an async method, it executes up to the first await
So it will correctly run all the way to the last line, then pause
If the async method never actually finishes, then it will never close the file
Throw a Debug.Log after the await line to find out
It does gets to the Debug.Log
The only thing I can think off is that it may be saving at the same time?
The time interval between the two saves ain't that long
Especially if these are both running anywhere but the main thread
Maybe it is trying to write while the first is still writing
if they're both run on the main thread, then they can't possibly happen "simultaneously"
but otherwise they could
Is there a way to check that?
you could add an artificial delay before you try to save again
Is there a way of like, "if already saving, waiting until finished saving"?
And then save again
a static field would work
Note that you'd need to be careful if you had several async methods running on several threads simultaneously
Otherewise, multiple threads could proceed simultaneously
i haven't written much thread-safe code in C# before
a static bool that indicates that you're currently saving, yes
What you really need is a mutex
this is all assuming that you're running these async methods on multiple threads
i don't know how you're actually running them
I'm just calling them honestly
Then why would you need
"if already saving, waiting until finished saving"
?
Are you saving asynchronously?
I mean, do I need to do anything when calling the function?
i'm calling it like any normal function
I thought this would already save async
Because the function is already async?
How would i get the current frame?
Code normally runs line by line on computers. It's not gonna by async unless you make it async.
I'm unclear on how calling an async method without actually awaiting it behaves
Is the function actually async? Can you share the code?
It's here
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.
The function is async
What I'm doing is... when I want to save, I just go... SaveWorld()
They await the writer in the end, so yeah, it should be async a little bit.
Then a static bool like Fen recommended is probably a good choice.
I recently did something very similar
I needed to write some Graphviz to a file
I wound up using Awaitable there
so I could just pass the method's return value to StartCoroutine
When starting saving set a bool to true. Set it to false after saving. Check if it's true already and don't start saving.
Since you only start the async methods from the main thread, that should be completely safe.
Though, if you want to queue saves, then you'll need additional mechanism, like an actual queue or counter of save requests.
then the error makes no sense
This scheme, I mean.
yeah, it is because it is trying to save while already saving
used this to check
Now I guess I just need to come up with a "wait to finishing saving, then save"
that would be the magic of the Mutex
Another bool for requestSave
the async methods can just sit there until the mutex unlocks
Oh cool, so it's like a queue?
A mutex will freeze the main thread
You shouldn't really mess with them unless dealing with Multithreading
What about Queue<Task>?
Semaphores are great for simple cases like this
Actually, a int SaveRequestCounter might be better than a bool.
Semaphore is gonna freeze the main thread too.😅
it's not, you can use WaitAsync to yield until the semaphore is available
Hmm. Sounds like overcomplicating things.
SemaphoreSlim is basically the int counter idea wrapped up in a class with methods to do that
I wonder if it's gonna work in the context of one thread though.
await saveSemaphore.WaitAsync();
try {
// do stuff
} finally {
saveSemaphore.Release();
}
yeah, i've used this in a game
Interesting.
it's probably not the most efficient way but in areas like saving files the extra allocations etc aren't really going to hurt
I still think that in this case a simple bool/int check would be enough.
so what I'm unclear about here is...
if you just run an async method and throw out the Task it returns
does that method ever actually finish running?
in this case, if you just ran...
SaveWorld();
you're tossing the Task
the task is just a handle to check the status of it, it runs whether you use it or not, but if you don't you won't get anything logged if an exception gets thrown
but where does it run?
unity updates all async methods that are running every frame
well, or it could be a worker thread if you were using one
wait, so it fundamentally changes how async behaves? that sounds very odd
I'd expect this if you made an Awaitable method that you passed to StartCoroutine
C# lets you install a "synchronization context" per thread which lets you change how "await" works, and unity has one that ensures all continuations keep happening on the unity main thread on successive frames rather than running in the background
ah, I see
Great, that's what I was looking for
i've been very murky on this stuff
hey i didn't know about the Awaitable class added in 2023, that's handy
probably better to use that than Task if you're on that version
yeah, I've been using that
with a flawed understanding, but a close enough one to make it work 😛
i have an async method that does a bunch of work, then awaits a few times as it creates and writes some text
It seems to be behaving
Unity runs it internally, similarly to a coroutine. There's an async state machine implementation that unity provides for executing the async methods.
wdym?
I was under the impression that the async method would just sit there forever until you explicitly awaited the task or ran it synchronously or something
That was incorrect.
and as we saw earlier, the method does finish running on its own
I envisioned it being more like this scenario
IEnumerator enumerator = SomeCoroutineMethod();
// do nothing with enumerator
that winds up doing literally nothing
you can force-wait for async code to finish, but it will also do so on its own and you can ask in each update loop if it did so on the handle of the async method
Hello, I'm currently working on a project that can dynamically help make a sort of train scheduler that I can use as a tool for optimizing playing a different game (Train Valley 2), where you tell it the stations/trains/paths/departures, and hopefully be able to edit one piece and it'll automatically update all the related variables. I'm making some decent progress, but I'm about at that point where I'm concerned I'm not following the best coding patterns to keep the code readable/debuggable in the future. My question is, does anyone have any recommended video's tutorials on the subject, or advice on what search terms would best be used to do self research?
Read on OOP and SOLID principles. That's about it. The skill of their correct application is coming with experience though.
nah, running it starts the work, the Task is just a handle so you can await it, or check when the work is done and get the result
if (Holding)
{
TargetDirection = TargetPoint.position - Grabbed.position;
Grabbed.transform.GetComponent<Rigidbody>().AddForce(TargetDirection * 2f, ForceMode.Acceleration);
}
How do I get the grabbed object to get exactly to the target point.
don't crosspost
But yeah, as mentioned in #💻┃code-beginner, use some sort of animation instead. This way you have more control.
i want it to be physics based
right. You can use joints for grabbing-behaviour
otherwise you're on the right track with this
You probably know this but it's important to note that an unawaited task is a real trap that will eat any exceptions thrown within
yup
if you ever see excpetions that never show up in the console, but do when breakpoint debugging, its in a task that never got awaited
I was wondering, why wouldn't unity catch the errors in the synchronization context(or whatever the thing that runs the async methods is called), and at least log the error messages? I assume that they're catching the errors, otherwise where would they be going?
if you write an async void method that's exactly what happens, otherwise C# puts the result into the Task and assumes you'll use it so it doesn't need to throw it itself
i would have to double check how it acts for things in other threads. but my assumption is its catching them to shove into the task result
Ah, that would explain it
it is nice, when you want the context of it in the stack
it's not really that unity is catching the exception, it's that an awaitable async method is a state machine that has a result/exception property set at the end
yeah, there's not much magic at all in UnitySynchronizationContext, it's pretty simple to implement given how C# works already
I see. I thought that's the part that unity was overriding to run them on the main thread, but I guess that was a wrong assumption.
handy tip: add CS4014 to your warn-as-error settings in csc.rsp to turn unawaited tasks into errors!
the sync context is doing nothing to define what thread it happens on
its just what allows it to return back to a method on a other frame with its state intact
good news though, awaiting breaks webgl builds completely so you dont need to worry about them
huh? you can use async/await just fine in webgl
thats clearly documeneted iirc
really? maybe with unitasks, but stuff just bricks my programs
i built a whole app around async code in webgl, unless they broke that since unity 2018
I'd imagine you can't use Task.Run, but async should still work.🤔
ah maybe its just threads
you can't use threads, but that's a totally separate thing, even though tasks are in the threading namespace
Unitytask does use threads I think.
yeah that would be it then
but yeah generally best to think of Tasks as just a handle for concurrent things. it says nothing about how its run
ive been just sticking to coroutines as much as possible but ill look more into it then
Interestingly, there's a disclaimer about it on the github page
Maybe it's the way you're using it?
someone did mention they do work on webgl, I've just not got around testing them
There's this too
Most UniTask methods run on a single thread (PlayerLoop), with only UniTask.Run(Task.Run equivalent) and UniTask.SwitchToThreadPool running on a thread pool. If you use a thread pool, it won't work with WebGL and so on.
UniTask.Run is now deprecated. You can use UniTask.RunOnThreadPool instead. And also consider whether you can use UniTask.Create or UniTask.Void.
So yeah, it might break on WebGL if you're using the threaded tasks
there are some pretty important things which don't work because they use threads, like Task.Run and Task.Delay, but once you know what to avoid the rest is totally safe and singlethreaded
so what's the benefit then over just using coroutines and yielding yourself?
really i consider the purposes to be very different
behind the scenes they're pretty similar but the async/await syntax is much nicer than trying to use enumerators for everything, think about stuff like exception handling and returning results, they compose much nicer
like if i want to be yielding frames or time will just use a coroutine
You can easily await multiple items in an extremely customisable way
find tasks are best suited to i am making a rest call, or asking a longer running thing for a result
and the setup of cancellable tasks is much more consistent and leads to more readable patterns that what you'd see with a coroutine
ah, I guess I've not ran into a scenario where I've needed those features
i hit that one all the time with addressables
I thought unity does its own async operations for addrssables
and oftne on setup for some rest api calls
they all have a Task property you can await too
It's really handy for interfaces. Making a modal which awaits for specific exit conditions, handles them differently, and is very robust and unbreakable
it still returns tasks you can use and i find it the most ergonmoic way to use addressables
yeah modals are nice
way better then having to give it callbacks and handle that rest of the flow in other functions
also if you do need to use multithreading, it's just about the easiest way to do it, you can easily await a small part of a method on a background thread and process the result back on the unity main thread in just a few lines of code and trying to do that in a coroutine is way more of a mess
even if you need a dedicated long running thread and not from the thread pool its great for that
just implement a task scheduler and task factory
it's funny but I've more experience in doing compute shaders than managing multi threads. I probably should consider picking up dots for my next project and get more acquainted
what game genre does dots compliment? rts?
any genre with 1000+ enemies at once
not even enemies just anything with lots of work where you can make systems that do not have a massive amount of dependencies
so a few systems can process in parallel with others
Almost all genres is my biased answer
I'd argue that the limitations are currently set by its limited feature set, and the development time required to work around that
If anyone wants to go down the rabbithole of what vertx means here, look up what caused the initial trouble with Cities: Skylines 2
(They had to create custom implementations of some important parts of the game cause DOTS didnt supply those yet and well, it didnt go as planned and was missing crucial features, like occlusion culling, cause of deadline troubles)
I mean it quite generally. A lack of integration with Timeline makes it difficult to connect cinematics with gameplay without developing tooling, for example.
It sounded like CS2 committed hard to their own implementation over switching to the built-in entities graphics, and some of their implementations were missing key features. I imagine their long development and difficulty turning with Entities development was what got them. But imo it has little to do with the current state of Entities
From what i got from the video i saw about it the release version they used did not implement rigged meshes yet and they had to do a custom implementation for that which caused trouble and when their development started they had to build a lot of implementations themselves, while they may have been available at time of release, they werent at time of development and such they kept their own implementation
Current state of entities is quite a lot more advanced, so I dont think a mishap of that caliber would happen again, but still its a represenation of what can happen with a missing featureset imo 😄
Was just a bad combo of deadline pressure, adapting tech a tad to early and testing oversights
Still quite far from anything resembling parity though unfortunately. But yeah, way better now than even .51 (and iirc CS2 was on something earlier than that?)
Hi guys, i 'm trying to detect collision of my collision and my cone (chich is a child of ghost) with the player and do two different action. but i cant detect the collision with the ghost
The script for the ghost is in the ghost.
void OnTriggerEnter(Collider other)
{
Debug.Log(other.transform.IsChildOf(transform));
if (other.transform.IsChildOf(transform) && other.CompareTag("Player")) {
Debug.Log("ON GHOST");
followingPlayer = true;
playerTransform = other.transform;
followTimer = 0f;
}
// else if (other.CompareTag("Player"))
// SceneManager.LoadScene(0);
}```
so do any of the debug logs print
o ok
Task.Run can work on webgl if you await it, which kinda beat the purpose await Task.Run(async ()=> {})
or if you make sure that the continuation will be guaranteed beck on the mainThread
you can work around this by making a single threaded custom syncContext that captures Unity's synccontext and switch to it when about to exit
it uses threadPool, and would switch to that if you tell it to, which essentially the same as Task.Run
Yeah, we figured it out in later messages.
Hi guys,
I'm having so much trouble trying to implement player movement relative to camera. My problem is, that whatever the implementation that I use, not of them seems to apply effect in my player movement.
This is my organization of my Update():
{
...
MovementRelativeToCamera(); <-----
...
MovePlayer(); <-----
...
} ```
void MovementRelativeToCamera()
{
Vector3 cameraForward = cameraTransform.forward;
cameraForward.y = 0f;
cameraForward = cameraForward.normalized;
Vector3 cameraRight = cameraTransform.right;
cameraRight.y = 0f;
cameraRight = cameraRight.normalized;
// Calculate movement direction based on camera orientation
movementDirection = verticalInput * cameraForward + horizontalInput * cameraRight;
movementDirection = movementDirection.normalized;
// Construct the text string
string text = "Camera Direction\n" +
"<color=blue>Z:</color> " + cameraForward.ToString("F2") + "\n" +
"<color=red>X:</color> " + cameraRight.ToString("F2") + "\n" +
"Movement Direction\n" +
"<color=green>X:</color> " + movementDirection.x.ToString("F2") + "\n" +
"<color=green>Y:</color> " + movementDirection.y.ToString("F2") + "\n" +
"<color=green>Z:</color> " + movementDirection.z.ToString("F2");
// Update the text component
cameraVector3Text.text = text;
}
void MovePlayer()
{
Vector3 velocity = movementDirection * speed;
velocity.y = ySpeed;
characterController.Move(velocity * Time.deltaTime);
}
Seems fine (if a little overcomplex). Did you assign cameraTransform properly?
Yes I did. I'm trying right now in a over simplified version. Just to check if a simple camera can effect the player movement.
Can someone explain how the OnSelect() method works? like does it get called only at the moment the UI is selected or for the whole duration while its selected?
At the moment it's selected
ah
now ik why my thing isnt working
thx
i was trying to do this but since its not called more than once it doesnt work. Is there any other way(another method or smtg) in which i can implement this?
Use Update to run code every frame
yea but then it updates the value of every single cell since the same script is attached to all
Use a bool variable to track if you're currently selected or not..
i want it to change only the one thats selected
Don't just do it blindly
Hi guys my player still runs even after it is dead i was working on my health script i didn't get any errors on it i even tried to change some things but it's still not helping
this my my health script
You'd have to show the code related to the player "running"
oh okay
this is player movement
i shared the health script because i was working on that and when i was running the game i got the issue
Ok so two things:
- You still have a dynamic Rigidbody when it dies which will freely continue moving
- You still have the animator going which will keep animating
Good day! How do you work on your Unity game using Git? I tried to push my code using LFS to GitHub but I quickly consumed 1gb LFS storage and now they want me to pay for a subscription. It seems like no one is talking about. Just everyone is saying: "just push your code to the GitHub...". And since I don't want to pay for subscription (if that was 1 time payment I could) I picked an alternative solution - local git repository. So I set up my local git repository on my local external drive. But when I wanted to push the project to this repo, also using GitLFS I got response: Remote "origin" does not support the LFS locking API. Consider disabling it with:
$ git config lfs.G:/git-repos/my-repo-name.git/info/lfs.locksverify false. I did JUST THAT, so i called git config lfs.<path_to_repo>/info/lfs.locksverify false in gitbash console, I also checked the file confif in the repo and it says: locksverify = false, but the popup always appears...
Hey guys, imtrying to make soldier ai that looks advanced and unpredictable.
Right now im trying to implement a flank behavior(with navmesh agents), but i cant figure out a way or any algorithms to do it.
I tried looking on the internet but i didnt find anything useful, only some paid unity navigation solutions that i cant purchase beacuse im in iran.
Any ideas on how i could implement flanking to a certain position? Or any resources that could help me figure it out?
Thanks for reading all that.
that sounds like a perfect task for ML Agents
I knew someone gonna say that.
I dont want to use ml agents beacuse
- i dont know how they work or how to use them
- i want fine control over my ai's behavior, using hierarchical finite state machines
- they are easy to learn, takes time but doable, CodeMonkey has a pretty good tutorial to get you started.
- You said unpredictable, ML agents will give you predictable unpredictable behaviour, nothing else will
Can they do stuff like a aoiding grenades, throwing grenades, reloading when the int 'ammo' on a refranced weapon component is 0, shoot at target,take cover when health is low and etc?
they could but that would be pointless because that is predictable behaviour, I was really talking about their movement behaviour
you can combine the two quite easily
Anyone experience errors like this when building a webgl project? Do you know any solutions?
I'm using visual studio code, and when i try to use things like the OnTriggerEnter2D function, the intellisense doesn't work. Do i have to add it manually? Is there anything I can do? Or should i just use visual studio.
hey guys so in my unity game i am adding a checkpoint for my player that when he dies he get's back to the checkpoint and before that the player has to go through the checkpoint to trigger it, the problem that i am having is that my player goes by the checkpoint and it was supposed to trigger the checkpoint and it runs the flag opening animation but doesn't do that and when the player dies he just spawns back to the same spot and doesn't move at all
this is the clip
cant do nothing without seeing codes
Did you configure the !ide with Unity?
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
i'll send
this is health script
player movement
player respawn
ctrl-f through your respawn script and figure out where you're calling your respawn method
yes
oh you have respawn method in your healthscript too eh
yes
Does respawning work correctly if you don't touch the checkpoint?
i.e. you don't get stuck
My player gets spawned on the place where he died last
instead of spwaning back to the checkpoint
yes
i even have the animations for the checkpoint flag to open i have recorded it but it doesn't get trigger when the player touches it
so the problem exists when you change checkpoints? Because that code isn't here
id start debugging such that you are changing checkpoints and those positions update
and i got the same problem like before that after my player dies he's health does not re generate to full and he just spawns and can do the assigned movements
in the player respawn?
oh, ok sorry im half awake. You do have it in a OnTrigger events
yes
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Checkpoint")
{
currentCheckpoint = collision.transform;
SoundManager.Instance.PlaySound(checkpoint);
collision.GetComponent<Collider2D>().enabled = false;
collision.GetComponent<Animator>().SetTrigger("activate");
}
}
i am sorry instead of active it is supposed to be appear
it still doesn't change a thing
the player moves even after it's dead
throw a debug it in to make sure you're actually triggering it
Like this:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Checkpoint")
{
Debug.Log("Has Triggered Checkpoint")
currentCheckpoint = collision.transform;
SoundManager.Instance.PlaySound(checkpoint);
collision.GetComponent<Collider2D>().enabled = false;
collision.GetComponent<Animator>().SetTrigger("activate");
}
}```