#archived-code-general

1 messages · Page 288 of 1

prime flax
#

to check which one it is and how to make it apply

rigid island
#

put a diff function inside the SO

#

each SO is different

lean sail
#

One SO can act as the base class, other child classes can override and implement behaviour

prime flax
#

alr ill try that, it sounds pretty plausible to implement

lean sail
#

The only downside to this would be if you need a physical model in game paired with this effect

dusky lake
#

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 😄

prime flax
#

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?

lean sail
lean sail
prime flax
#

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?

lean sail
#

Then drag it in from the inspector, the same way you would drag it in if you needed to reference a specific prefab

dusky lake
lean sail
#

I'm not entirely sure what you mean tbh, I dont use SO for mutable data

dusky lake
#

oh in that case its fine

faint hornet
#

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;
    }```
lean sail
#

those if statements are some insanity

swift falcon
#

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();
        }
    }
}```
cosmic rain
swift falcon
#

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

cosmic rain
swift falcon
#

im setting it incorrectly?!!

cosmic rain
cosmic rain
#

You're basically setting a white color there.

swift falcon
#

ah

swift falcon
cosmic rain
#

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.

swift falcon
#

my cells r images not buttons hence the problem

#

i wish i had created buttons lol

cosmic rain
swift falcon
#

yea

cosmic rain
#

Or Sprite renderers?

swift falcon
#

UI images

cosmic rain
#

Then you don't need a collider

swift falcon
#

but they dont hv any source image

cosmic rain
#

Nor physics raycaster

cosmic rain
swift falcon
#

they r simply empty UI images

cosmic rain
#

That's fine. As long as they're configured to accept raycasts.

swift falcon
#

ok

cosmic rain
#

But I'm not sure OnMouseUp is called in that case🤔

swift falcon
#

so i can remove the raycast from eventsystem n remove the colliders?

cosmic rain
#

Seriously, don't use it

swift falcon
#

what can I use then?

cosmic rain
#

IPointerExitHandler

#

And it's friends

#

Check the unity ui docs events section

swift falcon
#

Ok thx

#

Hv to go out now will check later

craggy shadow
#

Does anyone know how to fix this issue with WebGL? 😅

dawn nebula
#

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.

indigo verge
#

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?

cosmic rain
indigo verge
#
        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?)

fervent furnace
#
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++;
}
dawn nebula
cosmic rain
dawn nebula
# cosmic rain Sounds like several systems working together: ai planning to decide on the actio...

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.

cosmic rain
#

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

dawn nebula
# cosmic rain I don't know the whole context, so might be wrong, but in my opinion an Interac...

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?

cosmic rain
# dawn nebula I guess for a bit more clarity, in my mind the interactable itself isn't the one...

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.

indigo verge
#
    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?

dawn nebula
#

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

cosmic rain
signal moon
#

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");
        }
    }
}
signal moon
dawn nebula
cosmic rain
placid summit
#

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

hard viper
#

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.

delicate flax
#

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

thorny eagle
#

Hello guys i have a question what is better to achive ground check on 2D OnCollisionEnter2D or OverlapCircle()?

leaden ice
#

don't crosspost

hard viper
#

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.

delicate flax
# hard viper all actual changes to the level must go through BuildEditor, which allows me to ...

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.

stoic mural
#

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

delicate flax
#

textVariable.Count(c => c == specificDigit);

leaden ice
#

is this a string?

#

Or an int or something?

stoic mural
#

An int

leaden ice
#

Note that ints are stored in binary

#

so really the only "digits" it has are 1s and 0s

stoic mural
#

The number is a binary number

#

I’m using 0s and 1s

leaden ice
#

so you want to know how many 1s or 0s it has?

stoic mural
#

I just want to know how many 1s it has yeah

leaden ice
stoic mural
#

Ah perfect thank you

heady iris
swift falcon
#

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

leaden ice
swift falcon
#

huh?

leaden ice
#

and use the selectable colors (it has normal, hover, selected and disabled colors)

swift falcon
#

oh btw my cells r all ui images

leaden ice
#

Yes

#

Selectable is a UI thing

swift falcon
#

ohk

leaden ice
#

Add Component -> Selectable

swift falcon
#

ok ill check it out then

leaden ice
#

It will replace your pointer click thing

swift falcon
#

but any reason only some of them change?

leaden ice
#

No idea since you didn't share any code or other details

swift falcon
#

ok

leaden ice
#

maybe some are being blocked by something?

swift falcon
#

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?

leaden ice
leaden ice
#

selected is after you pressed it

swift falcon
#

ah ok

#

so then i wont need any code to change color yes?

leaden ice
#

right

swift falcon
#

alr so i used selectable instead, but some of the cells r still not changing...

leaden ice
#

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

swift falcon
#

Oh ok

versed spade
#

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

leaden ice
#

Also - would recommend you use LateUpdate for the parallax script

dawn nebula
#

What to do next given the current task, if it should continue the current, etc.

cosmic rain
dawn nebula
spring creek
dawn nebula
versed spade
# leaden ice Can you show your player movement script?
    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);
    }
versed spade
#

In the FixedUpdate.

leaden ice
#

Oh wait I see it

spring creek
regal epoch
#

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?

deft crown
#

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?

somber nacelle
#

sounds like you're rotating it via its transform

leaden ice
arctic plume
#

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
somber nacelle
#

you could set the Active Input Handling setting in the player settings to Both instead of just the Input System

heady iris
#

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.

somber nacelle
#

yeah the alternative would be to modify the asset so it uses the input system which may be a pain

heady iris
#

or just nuke the relevant code

#

code error commissar

#

BLAM

arctic plume
deft crown
rustic arch
#

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?

swift falcon
#

The rigidbody and Input handling

leaden ice
#

The roll is coming from centripetal force

leaden ice
#

your movement looks overall jittery too

rustic arch
#

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

leaden ice
# rustic arch I was thinking this

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

swift falcon
#

I was just about to say that

leaden ice
#

You're also calling MoveRotation in LateUpdate which is not correct:
_playerRigidbody.MoveRotation(_playerRigidbody.rotation * Quaternion.Euler(0, Mouse_X, 0 * Time.smoothDeltaTime));

deft crown
# leaden ice well you're rotating it by steering

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?

rustic arch
rustic arch
leaden ice
#

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

rustic arch
barren flicker
#

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

somber nacelle
#

obligatory: use cinemachine

barren flicker
#

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

heady iris
#

stuttering is probably going to happen with your camera controller too

barren flicker
#

with it just being newly installed

heady iris
#
        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?

barren flicker
#

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:

rustic arch
leaden ice
heady iris
#

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

leaden ice
barren flicker
#

or player.up*

rustic arch
rare radish
#

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!

heady iris
heady iris
barren flicker
heady iris
#

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

barren flicker
#

I fear it didnt fix it

#

In the function FollowTarget I added: transform.up = targetTransform.up;
still the camera doesnt rotate

heady iris
#

you probably want to copy the entire rotation

barren flicker
rustic arch
# leaden ice Try disabling your camera bobbing logic for the moment

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

late lion
# rare radish Hey, I don't know where to post this question, so please redirect me to another ...

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.

leaden ice
#

I.e. comment out CameraBobbing(inputDirection);

rustic arch
#

That got fixed

leaden ice
# rustic arch Yup

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;```
rare radish
# late lion Material Override will assign the internal video texture to a material property....

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?)

rustic arch
late lion
rustic arch
#

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

honest fulcrum
#

hi does someone know how to 'lerp' the reverb filter effect on an audio source?

leaden ice
honest fulcrum
#

I mean yea it's not an effect directly on the audio source

#

I'm talking about the reverb filter component

leaden ice
#

Looks like it has a bunch of different properties you could theoretically "lerp"

honest fulcrum
#

but I hoped I was missing some easier way to do that

static matrix
#

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?

leaden ice
honest fulcrum
leaden ice
honest fulcrum
static matrix
#

its a 2d game
but I can try with a vec3

leaden ice
#

Vec3 won't change anything

honest fulcrum
#

ah okay ignore me then

#

i made that mistake a week ago lol

leaden ice
#

body.velocity is a Vector2 if it's RB2D

static matrix
#

wait tf it isn't picking up the space key at the same time as the other 2

leaden ice
#

yep

#

N Key rollover

#

common keyboard limitation

honest fulcrum
leaden ice
honest fulcrum
#

exactly

leaden ice
#

but the symptoms would have been different

honest fulcrum
#

that's why i asked

leaden ice
#

but yeah it's not crazy to ask

#

you good

static matrix
#

how can I fix it???
can I fix it???
am I consigned to eternally being unable to go up and to the left???

leaden ice
#

or change the controls

static matrix
#

wrong one

#

thats annoying
come to think of it I did notice this in some other games I was playing

leaden ice
#

What keyboard are you using

#

is it a cheap one

static matrix
#

I can do space and WA but not space and Uparr Leftarr

#

its the one that came with my laptop

leaden ice
#

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

static matrix
#

I feel like up, left, and space are pretty common ones
how did lenovo not check

leaden ice
#

They probably didn't design this as a gaming computer

#

unless they did

#

in which case, shame

static matrix
#

ugh
im going to do what the above video did

#

why couldn't they have made it like backslash and forward slash or something

rustic arch
#

@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

leaden ice
#

Set it to whatever RB.velocity.y was already

static matrix
#

why would they set it to those keys

#

uuuuuuuuuugh

rustic arch
icy depot
#

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?

elfin tree
#

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?

icy depot
#

thank you box!

somber nacelle
lean sail
oak quarry
#

hey guys so for some reason i cant call CollectCoin(); in my player script anyone can help?

oak quarry
#

yea but its public

spring creek
#

You would have to reference the PortalManager and access the method through that

spring creek
oak quarry
#

how can i do that tho

spring creek
#

Once you have a reference, you do this:
myPortalManagerReference.CollectCoin()

#

With myPortalManagerReference obviously being a made up name for a variable

deft dagger
#

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 ?

naive swallow
pseudo wyvern
#

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.

oak quarry
#

so idk what to do

fair jackal
#

Try putting a debug.log to see if it even runs

lean sail
oak quarry
#

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

cursive basin
#

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 🫢

leaden ice
brave shadow
#

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?

Unity Learn

In this tutorial, you’ll: Revise the PlayerController script to store the value of collected PickUp GameObjects Create and configure UI Text Elements to display: The count value An end of game message

leaden ice
indigo verge
#

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?

leaden ice
#

That's an error with the serializer

brave shadow
#

does anyone know the roll a balll tutorial

leaden ice
#

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

indigo verge
#

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?

leaden ice
#

if the indices aren't in order you could be removing in any order which will indeed fuck things up

indigo verge
#

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?

leaden ice
#

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

indigo verge
#

Yeah, the indexes are in order, which is why I'm not sure what is going on here.

leaden ice
indigo verge
#

What should I use in place of it? I'm trying to delete unused inventory slot GameObjects.

leaden ice
#

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?

indigo verge
#

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?

leaden ice
#

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?

indigo verge
#

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

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

leaden ice
#

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)

indigo verge
#

Nope

#

Iitt stopped throwing errors

leaden ice
#

ok so it's related to your inspector somehow

#

if you comment out your custom editor does it also go away?

indigo verge
#

I'll try it with each. I have two, one that modifies a Debug Inventory ScriptableObject, and one that modifies a Database Scriptable Object.

hard viper
#

is the SO not being saved properly?

indigo verge
#

The issue SEEMS to solely be because of the custom editors adding buttons to my Scriptable Object for the Database and Inventories.

sick apex
#

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:

indigo verge
#

And they ONLY occur when I destroy certain gameobjects while certain other gameobjects are selected during runtime

sick apex
#

Its like it being rendered on top

rain minnow
sick apex
#

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

sick apex
#

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

leaden ice
foggy pasture
#

heya, is anyone familiar with a way to get rid of vertical sloping in marching cubes? I'd like to preserve horizontal sloping simultaneously

sick apex
#

This is my main camera:

dusk apex
#

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.

worldly zealot
#

k thx

heady iris
#

which kind of side-steps the entire problem by not having UVs at all

foggy pasture
#

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

heady iris
#

Oh, the vertical sloping in the actual geometry

#

I'm not clear what the difference between vertical and horizontal sloping is

foggy pasture
#

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

heady iris
#

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

foggy pasture
#

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

dusky lake
#

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

shell scarab
#

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.

cosmic rain
indigo verge
#
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.

spring creek
#

It won't affect the thing to the left of the equals, just gives you a local variable you can use

indigo verge
#

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)"?

spring creek
indigo verge
#

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?

eager pewter
#

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?

rigid island
# eager pewter So, Google seems to imply that the answer is "no" and that this has been an issu...
rigid island
#

@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);
    }```
eager pewter
#

Nothing platform agnostic, eh?

rigid island
#

sadly not for a state of a key without a keypress event

eager pewter
#

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?

rigid island
#

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

eager pewter
#

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

rigid island
#

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

soft ruin
#

shoot i did not see that my bad

eager pewter
rigid island
wicked karma
#

Guys what is better Unity or Godot for 3 D Games

rigid island
#

they're just tools

#

pick whatever feels comfortable for you

wicked karma
#

Yeah but unity is more polished that Godot but Godot has a better feel than Unity

#

So I'm not suree

rigid island
#

you basically answered your own question there

#

idk what you mean by "better feel"

wicked karma
#

Like it more comfortable while when I snooped around unity it felt more complex

rigid island
#

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

wicked karma
#

I think I'ma do godot

rigid island
wicked karma
#

Oh k

#

Thx for helping me I've been split on this decision

merry stream
#

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

latent latch
#

interfaces can be substituted for abstraction

#

more of a preference if anything, but both still cant be serialized on the editor anyway

scarlet viper
#

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)
neat forge
# merry stream this is the repo in question https://github.com/Unity3D-Projects/UnityGameplayAb...

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

scarlet viper
#

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

merry stream
neat forge
#

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

merry stream
#

ah i see

#

so on it's own, theres no point at all, they could just be defined without the interface

latent latch
#

there's an argument of implementing variance later on, which would require these indentical interface implementations

merry stream
#

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

swift falcon
#

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.

terse pier
#

is using Transform.Find() a bad habit? as it's basically hard coding and prone to failure if mistyped?

mellow sigil
#

yes, and for that reason among others

terse pier
#

so really assigning the inspector is better

mellow sigil
#

much better

latent latch
#

and if it's a reference created at runtime, you've got singletons for quicker access instead of having to search the scene

hard viper
#

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

tranquil canopy
#

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?

hard viper
#

Use the TNRD serializable interface plugin. Make an interface for your plugin to use like ISaveData which you can serialize.

#

That is my idea

swift falcon
#

how do i change the samples it doesnt say samples where it should

dark kindle
#
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?

leaden ice
#

If you only subscribed to performed you need to subscribe to canceled as well

leaden ice
dark kindle
#

@leaden ice

#

this what I have

leaden ice
#

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

dark kindle
leaden ice
#

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

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

leaden ice
#

or just a switch statement

#

or better branching logic

#
switch (context.phase) {
  case InputActionPhase.started:
    //
  case InputActionPhase.performed:
   //
  case InputActionPhase.canceled:
   //
}```
hard viper
#

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

dense crow
#

what is better practice between public static GameManager Instance { get; private set; } and private static GameManager instance; public static GameManager Instance

latent latch
leaden ice
quiet surge
#

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

somber nacelle
#
  1. have some patience next time. i was about to answer you in the beginner channel before you deleted the question
  2. 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
heady iris
#

i didn't know that you'd get an error from applying an equally restrictive modifier, interesting

quiet surge
quiet surge
somber nacelle
#

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

heady iris
#

also, the tutorial did not write the exact same thing, because then it would've been a compile error

quiet surge
#

i am sorry why are you being rude?

heady iris
#

unless the tutorial literally just doesn't work, of course, which is always a possibility

somber nacelle
quiet surge
#

Sorry

heady iris
#

do you not understand what an "access modifier" is?

quiet surge
#

i do

heady iris
#

what is unclear about the error message, then?

quiet surge
#

Nothing i understood

#

should have had some patience

#

Thankyou for helping me

hard viper
#

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…

latent latch
#

bitmask

hard viper
#

that sounds like it would not help my code be cleaner :/

simple egret
#

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

hard viper
#

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):…

simple egret
#

That works

latent latch
#

I thought you couldnt do fallthrough in c#

hard viper
#

like a clean switch on a value tuple

hard viper
#

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;

hard viper
simple egret
#
switch ((a, b))
{
    case (1, true):
      break;
}
hard viper
#

ty. just what I was looking for

simple egret
#

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)

silver vector
#
    {
        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)
heady iris
#

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

ancient holly
#

why is that error appearing?

heady iris
#

Perhaps you have another instance of the component that's missing the reference

#

or something is setting the field to null at runtime

ionic stone
#

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.

latent latch
#

composition

heady iris
#

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.

latent latch
#

isaac has a lot of edge cases so I expect a lot is composite

ionic stone
#

Okay, cheers, ill have a look at it. First time im hearing the word xd

latent latch
#

basically,

if(chain)
if(fork)
if(bounce)

tacit loom
#

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

heady iris
#

two objects with rigidbodies on them, presumably?

#

is this 3D physics or 2D physics?

tacit loom
#

2d physics

heady iris
#

and a FixedJoint2D didn't do what you wanted?

tacit loom
heady iris
#

apparently it'll work better if you put the joint on the heavier object, so check that if the two rigidbodies have different masses

tacit loom
#

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"

heady iris
#

both objects are moving at the same time, you mean?

#

together

tacit loom
#

blue is the player

heady iris
#

rather than wandering off in different directions

tacit loom
#

yellow is a glue thats stick to it on collision

heady iris
#

The colliders are overlapping, which could be causing weird physics problems

tacit loom
#

hmm, how can I fix it?

knotty sun
#

why not just compile the dll directly into your project?

heady iris
#

I'm not sure what the easiest fix would be, though

tacit loom
#

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

steep knot
#

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.

leaden ice
#

The details are important

steep knot
#

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

leaden ice
#

Typically you can say like if(Camera.current == SceneView.camera) return; or something along those lines

steep knot
#

The layer "Mask" contains objects rendered where the player can see and the other layer in the "see through" pass includes the other objects

magic briar
#

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? UnityChanDown 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? :/

thick terrace
swift falcon
#

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

magic briar
bold talon
#
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
magic briar
thick terrace
arctic plume
#

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

thick terrace
#

onTriggerEnter -> OnTriggerEnter

arctic plume
#

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

deft dagger
#

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

thick terrace
thick terrace
swift falcon
#
 
 
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.

deft dagger
thick terrace
deft dagger
#

the scripting backend in uwp is set to IL2CPP and i cant change it

#

i can change it in normal windows platform

thick terrace
#

by "don't work" do you mean it doesn't compile or you get an error?

deft dagger
#

so i dont exactly know

#

oh you mean compiling as in make the build ?

thick terrace
#

well, probably time to change that logic and see if it throws a different error 😛

knotty sun
#

so what if you get a HTTP error?

deft dagger
thick terrace
#

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

deft dagger
#

is it this ?

thick terrace
#

no, that's just to stop it requiring HTTPS

#

the bit i linked is the capabilities section

deft dagger
#

oh this ?

thick terrace
#

that's what i linked yup

deft dagger
#

umm do you know which one exactly i have to tick? there are a llot 😅

sharp acorn
#

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?

sharp acorn
rigid island
#

let me find link h/o

sharp acorn
sharp acorn
rigid island
thick terrace
deft dagger
thick terrace
#

hope it works, like i said it's been a long time since i touched UWP 😅

magic briar
thick terrace
#

looking at the nuget package, there's 4 native dlls

magic briar
#

still cant find the cameras, but no errors UnityChanCheer

thick terrace
#

glad to hear it! good luck with the rest

swift falcon
#

Any way of creating a UML/Class diagram with Visual Studio with an entire Unity project?

heady iris
#

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

heady iris
#

Visual Studio has the Class Designer, which may do what you want

brazen widget
#

How would i add a keyframe to a material via script?

rigid island
#

wdym

heady iris
#

you can animate material properties

#

I'm a little unclear about "adding a keyframe" via script, though

#

is this an editor script?

brazen widget
#

let me get an example

heady iris
#

I haven't done that from code before myself

#

but I can't imagine it's any different than keyframing anything else

brazen widget
#

something like this

#

where i move this gizmo and it will apply the animation the material shader vector

pastel depot
#

can someone help, im trying to change my Scripting Runtime Version to .NET 4.x but i dont have it

hard viper
brazen widget
#

Lmao

hard viper
outer apex
#

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

heady iris
#

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

outer apex
#

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

lament cedar
#

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?

celest iron
#

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:

#

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.

heady iris
#

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

celest iron
#

ok

#

1 sec

celest iron
#

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

heady iris
#

Especially if these are both running anywhere but the main thread

celest iron
#

Maybe it is trying to write while the first is still writing

heady iris
#

if they're both run on the main thread, then they can't possibly happen "simultaneously"

#

but otherwise they could

celest iron
#

Is there a way to check that?

heady iris
#

you could add an artificial delay before you try to save again

celest iron
#

Is there a way of like, "if already saving, waiting until finished saving"?

#

And then save again

heady iris
#

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

celest iron
#

static bool IsSaving?

heady iris
#

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

celest iron
#

I'm just calling them honestly

cosmic rain
#

Then why would you need

"if already saving, waiting until finished saving"

?
Are you saving asynchronously?

celest iron
#

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?

brazen widget
#

How would i get the current frame?

cosmic rain
heady iris
#

I'm unclear on how calling an async method without actually awaiting it behaves

cosmic rain
celest iron
#

The function is async

#

What I'm doing is... when I want to save, I just go... SaveWorld()

cosmic rain
#

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.

heady iris
#

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

cosmic rain
heady iris
#

Since you only start the async methods from the main thread, that should be completely safe.

cosmic rain
#

Though, if you want to queue saves, then you'll need additional mechanism, like an actual queue or counter of save requests.

celest iron
celest iron
#

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"

heady iris
#

that would be the magic of the Mutex

cosmic rain
#

Another bool for requestSavethinksmart

heady iris
#

the async methods can just sit there until the mutex unlocks

celest iron
#

Oh cool, so it's like a queue?

cosmic rain
#

A mutex will freeze the main thread

#

You shouldn't really mess with them unless dealing with Multithreading

celest iron
#

What about Queue<Task>?

heady iris
#

oh, you're absolutely right

#

god I really need to properly grok async

thick terrace
#

Semaphores are great for simple cases like this

cosmic rain
#

Semaphore is gonna freeze the main thread too.😅

thick terrace
#

it's not, you can use WaitAsync to yield until the semaphore is available

cosmic rain
#

Hmm. Sounds like overcomplicating things.

thick terrace
#

SemaphoreSlim is basically the int counter idea wrapped up in a class with methods to do that

cosmic rain
#

I wonder if it's gonna work in the context of one thread though.

thick terrace
#
await saveSemaphore.WaitAsync();
try {
  // do stuff
} finally {
  saveSemaphore.Release();
}
#

yeah, i've used this in a game

cosmic rain
#

Interesting.

thick terrace
#

it's probably not the most efficient way but in areas like saving files the extra allocations etc aren't really going to hurt

cosmic rain
#

I still think that in this case a simple bool/int check would be enough.

heady iris
#

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?

heady iris
thick terrace
#

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

heady iris
#

but where does it run?

thick terrace
#

unity updates all async methods that are running every frame

#

well, or it could be a worker thread if you were using one

heady iris
#

wait, so it fundamentally changes how async behaves? that sounds very odd

heady iris
thick terrace
#

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

heady iris
#

ah, I see

#

Great, that's what I was looking for

#

i've been very murky on this stuff

thick terrace
#

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

heady iris
#

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

cosmic rain
# heady iris but where does it run?

Unity runs it internally, similarly to a coroutine. There's an async state machine implementation that unity provides for executing the async methods.

heady iris
#

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

dusky lake
#

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

steep patrol
#

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?

cosmic rain
quaint rock
swift falcon
#
 
 
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.

woeful spire
swift falcon
#

i want it to be physics based

woeful spire
#

right. You can use joints for grabbing-behaviour

#

otherwise you're on the right track with this

quartz folio
quaint rock
#

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

cosmic rain
#

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?

thick terrace
quaint rock
cosmic rain
#

Ah, that would explain it

quaint rock
#

it is nice, when you want the context of it in the stack

thick terrace
#

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

quaint rock
#

yeah this is regular C# behaviour

#

not something weird unity is doing

thick terrace
#

yeah, there's not much magic at all in UnitySynchronizationContext, it's pretty simple to implement given how C# works already

cosmic rain
#

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.

thick terrace
#

handy tip: add CS4014 to your warn-as-error settings in csc.rsp to turn unawaited tasks into errors!

quaint rock
#

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

latent latch
#

good news though, awaiting breaks webgl builds completely so you dont need to worry about them

thick terrace
quaint rock
latent latch
#

really? maybe with unitasks, but stuff just bricks my programs

thick terrace
#

i built a whole app around async code in webgl, unless they broke that since unity 2018

cosmic rain
#

I'd imagine you can't use Task.Run, but async should still work.🤔

quaint rock
#

ah maybe its just threads

thick terrace
#

you can't use threads, but that's a totally separate thing, even though tasks are in the threading namespace

cosmic rain
quaint rock
#

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

latent latch
#

ive been just sticking to coroutines as much as possible but ill look more into it then

cosmic rain
#

Interestingly, there's a disclaimer about it on the github page

#

Maybe it's the way you're using it?

latent latch
#

someone did mention they do work on webgl, I've just not got around testing them

cosmic rain
#

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

thick terrace
latent latch
#

so what's the benefit then over just using coroutines and yielding yourself?

quaint rock
#

really i consider the purposes to be very different

thick terrace
#

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

quaint rock
#

like if i want to be yielding frames or time will just use a coroutine

quartz folio
#

You can easily await multiple items in an extremely customisable way

quaint rock
#

find tasks are best suited to i am making a rest call, or asking a longer running thing for a result

quartz folio
#

and the setup of cancellable tasks is much more consistent and leads to more readable patterns that what you'd see with a coroutine

quaint rock
#

yeah was going to mention easy cancelation

#

also Task.WhenAll and its friends

latent latch
#

ah, I guess I've not ran into a scenario where I've needed those features

quaint rock
#

i hit that one all the time with addressables

latent latch
#

I thought unity does its own async operations for addrssables

quaint rock
#

and oftne on setup for some rest api calls

thick terrace
quartz folio
#

It's really handy for interfaces. Making a modal which awaits for specific exit conditions, handles them differently, and is very robust and unbreakable

quaint rock
#

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

thick terrace
#

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

quaint rock
#

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

latent latch
#

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

merry stream
#

what game genre does dots compliment? rts?

quaint rock
#

many

#

just about how you do your systems and how its all split

latent latch
#

any genre with 1000+ enemies at once

quaint rock
#

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

spring creek
quartz folio
#

I'd argue that the limitations are currently set by its limited feature set, and the development time required to work around that

dusky lake
quartz folio
#

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

dusky lake
#

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

spring creek
crimson vault
#

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);
    }```
prime sinew
crimson vault
#

Yeah but cant find the problem, i dot it with a raycast now

#

it works fine

prime sinew
#

o ok

craggy veldt
#

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

craggy veldt
cosmic rain
ebon warren
#

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);

}

leaden ice
ebon warren
#

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.

swift falcon
#

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?

swift falcon
#

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?

leaden ice
swift falcon
#

yea but then it updates the value of every single cell since the same script is attached to all

leaden ice
#

Use a bool variable to track if you're currently selected or not..

swift falcon
#

i want it to change only the one thats selected

leaden ice
#

Don't just do it blindly

swift falcon
#

oh alr

#

works now, tysm

quiet surge
#

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

leaden ice
quiet surge
#

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

leaden ice
#

Ok so two things:

  1. You still have a dynamic Rigidbody when it dies which will freely continue moving
  2. You still have the animator going which will keep animating
quiet surge
#

Okay

#

thankyou

silent harness
#

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

next salmon
#

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.

knotty sun
next salmon
knotty sun
#
  1. they are easy to learn, takes time but doable, CodeMonkey has a pretty good tutorial to get you started.
  2. You said unpredictable, ML agents will give you predictable unpredictable behaviour, nothing else will
next salmon
knotty sun
#

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

barren void
#

Anyone experience errors like this when building a webgl project? Do you know any solutions?

swift falcon
#

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.

quiet surge
#

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

latent latch
#

cant do nothing without seeing codes

rain minnow
tawny elkBOT
quiet surge
#

this is health script

#

player movement

#

player respawn

latent latch
#

ctrl-f through your respawn script and figure out where you're calling your respawn method

quiet surge
#

yes

latent latch
#

oh you have respawn method in your healthscript too eh

quiet surge
#

yes

heady iris
#

Does respawning work correctly if you don't touch the checkpoint?

#

i.e. you don't get stuck

quiet surge
#

My player gets spawned on the place where he died last

#

instead of spwaning back to the checkpoint

latent latch
#

i'd try debugging your postions

#

good time to learn how to use debug.log

quiet surge
#

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

latent latch
#

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

quiet surge
#

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

latent latch
#

oh, ok sorry im half awake. You do have it in a OnTrigger events

quiet surge
#

yes

latent latch
#
    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");
        }
    }
quiet surge
#

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

latent latch
#

throw a debug it in to make sure you're actually triggering it

quiet surge
#

in health script i added

#

dead = false;

latent latch
#

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");
      }
  }```