#archived-code-general

1 messages Β· Page 301 of 1

cosmic rain
#

You'd use serialize field attribute with private fields only.

#

It means converting the data to a savable format.

neon smelt
#

hmmm... so it's in a savable format. that's good! but how do I actually save it?

cosmic rain
#

You can use a serializer like JsonUtility to save the data to a file.

#

What are you trying to do actually?

neon smelt
#

save all this data out to the scene

cosmic rain
#

A save system? Or just apply changes during play mode?

neon smelt
#

I think maybe it's because I"m doing it at runtime

#

if I did this at editor time, would it save?

cosmic rain
#

Depends on what you're actually doing.

neon smelt
#

or yes, apply changes during play mode

cosmic rain
#

Well, you can copy the component values at play time and paste them after exiting the play mode.

#

You're not really supposed to edit the scene at runtime.

neon smelt
#

perhaps I need to make this thing an editor script, and that will populate this stuff at editor tie

#

time

#

and therefore be saved for play

#

but thank you, knowing you shouldn't edit the scene at runtime is helpful info indeed!

cosmic rain
#

Yeah, you'd write an editor script if you want to populate the data.

neon smelt
#

OK perfect, that's what I'll do

#

thank you very much for your help

gilded pendant
#

When pressing ESCAPE, everything works. the PauseMenu opens, but on the buttons there is no hover effect and when i press leftclick my mouse disappears. can someone help?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PauseMenu : MonoBehaviour
{

    public GameObject PausePanel;

    // Update is called once per frame
    void Update()
    {
        Pause();
    }

    public void Pause()
    {
        if(Input.GetKey(KeyCode.Escape))
        {
            PausePanel.SetActive(true);
            Time.timeScale = 0;
        }
    }

    public void Continue()
    {
        if(Input.GetKey(KeyCode.Escape) && PausePanel.activeSelf)
        {
            PausePanel.SetActive(false);
            Time.timeScale = 1;
        }
        PausePanel.SetActive(false);
        Time.timeScale = 1;
    }

    public void backToMainMenu()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
    }
 }
somber nacelle
#

you aren't actually unlocking the mouse cursor so when you click again it goes back to being locked. pressing escape only releases it in the editor

#

as for why you aren't getting hover effects, either it's because the time scale is preventing the UI from updating for whatever reason, or you don't have an event system in the scene oh wait this is totally caused by the mouse not being unlocked lol

gilded pendant
cold seal
#

Are there any alternatives to Unity.Mathematics.noise for generating terrain using Job System? Its painfully slow.

charred robin
#

Why is my character controller floating? Actually pulling my hair out... None of my code is attached. Just using Unitys character controller atm.

somber nacelle
#

charactercontroller and rigidbody do not mix. and you have to manually apply gravity to the CC

deft crown
#

In the game I'm making, in the scene where the gameplay is, I have several AudioSource. The problem I have is that the first time the scene is loaded, coming from another one, it can be heard, but if I reload the scene, coming from another one, it can't be heard.
Does anyone know what could be happening? I can take screenshots if necessary.

charred robin
somber nacelle
#

move with one or the other. do not put both on there

#

also you should really not be doing multiplayer if you aren't even familiar enough with the engine to move an object

charred robin
#

I've just not used Unitys character controller before.

charred robin
# deft timber yikess

yeah we have our own ways of handling movement etc so never had to use unity's character controller

deft timber
#

You are a developer professionaly for 6 years and couldn't Google that you don't mix character controller with rigid body, got it

somber nacelle
#

I'd like to know where these jobs are that hire people not very familiar with the most common issues people face in the engine

thick terrace
#

that's not so weird? the first 3 years of my career were entirely spent on games without any physics lol

charred robin
deft timber
#

yea - engine issue

craggy veldt
charred robin
vapid condor
charred robin
vapid condor
#

becuase there are moments where you could techically use both

#

for example you use the CC for movement, and have a grapling hook that will make use of the RB, but you toggle the components between them

fiery saddle
#

I have component of player and another component for jumping
First message is Player Start method
then Player Update
then Jump Update
and i get error becasue Jump Start has references

BUT this doesnt happens always. sometimes start of Jump is called right after Start of Player, why?

vapid condor
#

the order of execution for scripts are basically random

somber nacelle
#

do not rely on specific ordering of component's Start and other messages. unless you specify an execution order it is not guaranteed. and if you find you have to modify the execution order a lot then you are designing your systems poorly

fiery saddle
#

I never has this shit before, when player was in scene, now switched to instantiating him, and it happens 50% of time

vapid condor
#

there is no guarantee that the start for jump is called before the start of player

#

like i said, it basically random

#

unless like boxfriend said you specify a custom execution order which is not a good thing to do for scripts like that

fiery saddle
#

I moved these references to Awake function
I know Start is random but Update? i though Update is always after start on same object

somber nacelle
#

Update will always come after Start on the same object. but that doesn't mean one object's Start will happen before another object's Start and/or Update

fiery saddle
#

Well object yeah, but components on same object?

vapid condor
#

yes components on the same object

fiery saddle
#

I mean obviously not, but i thought otherwise

vapid condor
#

those are also ran in a random order

fiery saddle
#

Anyway, moved references to the Awake and now its okay

#

thankfully really easy fix

vapid condor
#

yeah you should use awake for initializing stuff most of the time

somber nacelle
#

use Awake to initialize an object's own variables, use Start to reach out to other objects. This will ensure that variables are already initialized before other objects start trying to access them

placid summit
#

Only talk to woke objects!!

rocky jetty
#

I made some code for a camera object to zoom in if something enters its trigger zone. However, it also zooms in if it enters the triggerzone of another object, and I don't want that. How can I fix that? can I specify that in the OnTriggerStay method or...

meager pendant
#

nothing feels better than writing everything in 1 file then finishing it and separating it into multiple files

#

this was all like 3 files and 300-500 lines each

thick terrace
#

Refactor>Extract Class my beloved

#

rider feels like cheating sometimes ☺️

meager pendant
#

its almost masochistic how much i detest using anyone elses tools unless i have to

#

i dont even use lookat i do it myself bruh

devout silo
#

thanks!

placid summit
winter frost
#

is it fine practice to have a singleton monobehaviour that holds references to a bunch of scriptable objects? i’m making a weapon system where scriptable objects represent a weapon in the inventory but hold reference to prefabs that are the actual weapon themselves

winter frost
#

oh hell yeah

#

good to know, thank you!

#

was worried that i was doing something stupid haha

surreal cloak
#

what is the best way to check if a nav mesh agent has reached his destination cuz this isnt working

        {
            if (animator.runtimeAnimatorController != idle)
            {
                animator.runtimeAnimatorController = idle;
                agent.isStopped = true;
                Debug.Log("Agent has reached its destination.");
            }
        }```
meager pendant
#

well

#

how would i use it in unity

#

-lua user

vagrant blade
#

You don't, you use it in C#. It's an organizational thing.

meager pendant
craggy veldt
#

you can think of namespaces in c# are like "scope"

marsh geode
#

I'm making a settings system for my game using reflection. I get all the fields of the settings script on start:

Type settings = typeof(Essential.Settings);
FieldInfo[] info = settings.GetFields(BindingFlags.Public | BindingFlags.Instance);```
Then make UI out of them:
```cs
if (GetAttributes<Slider>(property))
{
    Instantiate(slider, settingsView);
}```
which works perfectly and all, but I'm not sure on how I can create new settings out of them:
```cs
public void Apply()
{
    var settings = new Essential.Settings()
    {
        // ..?
    };
    SaveManager.CreateSettings(settings);
}```
I essentially need to convert the UI back to fields, and I don't know how to do that in order to create a class
I also have this dictionary in case it ends up being useful:
```cs
public Dictionary<Transform, FieldInfo> settingsUI = new();```
hidden locust
#

That seems a bit overkill

#

Using Reflection, that is.

#

I essentially need to convert the UI back to fields, and I don't know how to do that in order to create a class
Surely you don't mean creating new fields, right?

soft shard
# rocky jetty I made some code for a camera object to zoom in if something enters its trigger ...

You can get Collider info with OnTriggerStay, which can give you access to the object that collider is attached to, and things like layer, tag and scripts, you could use any one of those to differentiate your camera from the objects that should trigger the action, and if all of your triggers are on the same layer you can have them ignore the layer or ignore interaction between specific colliders with the Physics class

hidden locust
spring creek
rocky jetty
marsh geode
hidden locust
#

I mean, you could use a dictionary or list or something of structs

marsh geode
hidden locust
#

like rather than have 5 raw floats on the Settings class and using reflection to get them, have a struct like public struct MySetting { string fieldName; float value; } and then have a collection like a List<MySetting>

marsh geode
#

Yeah, but then i'd have to do more manual work

#

because now I can just add a field to this class and an attribute and everything but the logic works

chilly obsidian
#

camera jittering when rotating it with the player model at the same time any help as to why? Im pretty sure its the timing of how I rotate both but Im not sure how to fix it, I have tried multiple ways

void Update()
    {
        // Checks to see if player is touching ground layer
        grounded = Physics.Raycast(transform.position, Vector3.down, height * 0.5f + 0.2f, ground);

        MyInput();
        DragControl();

        SpeedControl();
        Hotkeys();
    }

private void FixedUpdate()
    {
        MovePlayer();
    }

    private void LateUpdate()
    {
        CameraMove();
    }```



```cs
private void MovePlayer()
    {
        rb.MoveRotation(orientation.rotation);

        if (grounded)
            rb.AddForce(playerVelocity.normalized * currSpeed, ForceMode.Impulse);
        else if (!grounded)
            rb.AddForce(playerVelocity.normalized * currSpeed * airMultiplier, ForceMode.Impulse);
    }
private void CameraMove()
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * sensitivityX * Time.fixedDeltaTime;
        float mouseY = Input.GetAxisRaw("Mouse Y") * sensitivityY * Time.fixedDeltaTime;

        if (cameraPlayer != null)
        {
            rotationY += mouseX;
            rotationX -= mouseY;
            rotationX = Mathf.Clamp(rotationX, -70f, 70f);

            cameraPos.rotation = Quaternion.Euler(rotationX, rotationY, 0f);
            orientation.transform.rotation = Quaternion.Euler(0, rotationY, 0);
        }
    }
hidden locust
#

If you want to add more logic around how settings are grouped or add metadata to the fields (like min / max values for the sliders) a struct gives more control and flexibility

clear umbra
#

Can I apply a force on a rigidBody inside of the FixedUpdate function?
for some reason my code works when I put it in Update but fails to move my rigidbody at all when I use FixedUpdate.

#
void FixedUpdate()
    {
        if (!isLocalPlayer) return;

        var moveX = Math.Clamp(movementJoystick.Horizontal, -1.0f, 1.0f);
        var moveY = Math.Clamp(movementJoystick.Vertical, -1.0f, 1.0f);

        var shootX = Math.Clamp(shootingJoystick.Horizontal, -1.0f, 1.0f);
        var shootY = Math.Clamp(shootingJoystick.Vertical, -1.0f, 1.0f);

        var move = new Vector3(moveX, 0.0f, moveY);
        var shoot = new Vector3(shootX, 0.0f, shootY);
        
        CommandUpdateMovementJoystick(moveX, moveY);
        CommandUpdateShootingJoystick(shootX, shootY);
        
        Debug.Log(move);

        //Apply movement
        if (move.magnitude > 0.1)
        {
            rb.AddForce(move * Acceleration);
        }

        //Clamp the velocity
        if (rb.velocity.magnitude > MaxSpeed)
        {
            rb.velocity = Vector3.Normalize(rb.velocity) * MaxSpeed;
        }

        if (shoot.magnitude > 0.1)
        {
            
        }
    }
#

When logging the move vector it indeed has a magnitude greater than 0.1

marsh geode
green ice
#

Hi guys,how can i solve this problem?

knotty sun
hidden locust
hidden locust
#

Rather than direct File IO

#

You only need to bother with writing to files for larger data chunks (>2kb)

green ice
hidden locust
#

@spring creek why not?

#

(I'm a bit of a noob so I'm genuinely curious)

spring creek
hidden locust
#

Never?

spring creek
#

Playerprefs are ALRIGHT (i guess) for things like game settings like volume and resolution

#

But even that I prefer files

#

If you only need to save a single value, like score, it would be fine. But may as well use files STILL imo

hidden locust
#

I would think something as simple as setint / getint would be preferable to having to write an int to a file and then read it back (way more code to write in the latter scenario)

spring creek
somber nacelle
#

sure they are easier. but playerprefs writes to the registry on windows. do you really want to pollute the registry with your meaningless data that could just as easily be written somewhere sensible?

marsh geode
lean sail
spring creek
#

Yeah, honestly, playerprefs is gonna require more code unless you are only saving a COUPLE values

Each value needs at least two lines of code (get and set, assuming you only do that in one place each) So 5 values is already the same amount as bawsi's solution

lean sail
#

Plus if you try to save anything else, you have to either convert or use a file anyways

#

Playerprefs only handles basic types

wheat bramble
#

I am trying to do a simple mesh drawing using drawmeshnow (working with gizmos with materials) to make the 2d bounding box from a 3d (vertex defined) bounding box (not actual bounding box).
No matter what i do the shape will consistently be slightly offset and i cant figure out why
https://discussions.unity.com/t/drawing-a-screen-space-rectangle-with-graphics-drawmeshnow/12873 (closest thing to what i need i found)
the code isnt crazy its just a static shape
Then i use ```cs
Camera camera = SceneView.currentDrawingSceneView.camera;
//Translation using camera.WorldToScreenPoint
//Find Extremities like above
//Then using camera.ScreenToWorldPoint

hidden locust
spring creek
#

Each playerprefs system needs to be fairly bespoke though, meaning you will need to rewrite parts of it for each project

soft shard
# hidden locust I don't understand... if you do a file-based approach you have to write custom c...

If you de/serialize with generics T then you would only need 1 generic function that takes in your data and the path of the file for serializing, and just the path for deserializing, you get a object back which you can cast to T, and T can be any data type you want, any serialized class or struct, for example, you could do something like Save(somePlayerStatsRef, somePath) or Load<PlayerStats>(somePath), being generic functions that handle de/serialziation respectively, be it JsonUtility, or more robust solutions like Newtonsoft JSON

neon smelt
#

I'm populating this data at Editor time, but on play it clears. It also clears when the scene is reloaded. Is there a way of getting this to stay around and get saved like any game object? I know I cam serialize to disc but it just seems like there should be a simpler way

spring creek
neon smelt
#

I do! from an editor script

#

an editor... extension I think it's called?

#

oh you mean at runtime?

spring creek
tawny elkBOT
neon smelt
#

it's a lot of code

#

but you're saying this kind of data should stay around?

spring creek
neon smelt
#

I just checked and nothing is changing it, but it all clears out on play

#

the method is private and used in one place. a debug print shows this also

#

perhaps I need to mark it as dirty

#

EUREKA

#

we learned something here today. WHO KNOWS WHAT

spring creek
neon smelt
#

but it worked

spring creek
#

Oh dang, ignore that last message haha. Well, nice

neon smelt
#

thanks for the help though!

#

very useful to know it SHOULD have been working

#

this was the hardest thing about all this. so many options but no idea which to go with

spring creek
#

Well, glad I could do that at least

meager pendant
#

how could i make it so the ui's fade in when they are instanced (i know how to do it, i just am not sure how I can fade in the the children of the instance with it)

simple egret
fresh ibex
#

Hey all! New here! Is there a way to load Motions into a scriptable object and then dynaically assign those Motions into the Animator when the player changes weapons to the scriptable object?

hidden locust
#

So I was trying to implement a file saving system but I am getting IOException: Sharing violation on path when I try to open a streamwriter

#

is there a best practices for reading / writing files?

#

using a new Streamwriter(path)

somber nacelle
#

is that on the ctor for StreamWriter? because IOException thrown from the ctor should mean that the path contains an invalid name

hidden locust
#

might have missed closing a stream...

simple egret
#

Most likely there was an attempt in opening the file which was not closed properly, so you now have a dangling stream open

#

Always use using statements when dealing with streams

#

They ensure the stream is closed and disposed of properly, even if an exception occurs

#
using (FileStream fs = File.OpenWrite(...))
{
    // use 'fs'
}
// 'fs.Dispose()' called implicitly when execution leaves the block
hidden locust
#

yeah, my mistake for copying and pasting Microsoft's example code which didn't bother using usings lol

somber nacelle
#

alternatively a using declaration, which is nearly the same thing but doesn't create another scope, is also an option.
using var stream = new StreamWriter(whatever);
and then it disposes of it when the local variable is also disposed (so at the end of the method typically)

chilly surge
#

Using declaration should be preferred most of the time yeah, but streams are kind of an outlier because some of them have certain behaviors on disposal that you want explicit control of, and using statements allow that.

#

I've been bitten once by compression stream only writing the final footer on disposal, which happens after I return and thus causing the return value to be missing the footer.

hidden locust
#

also are there any performance impacts I should be mindful of? I have a slider for a volume setting and I would be writing the value to the file every frame while it's sliding :/

#

I was thinking it might be safer to only write the value once every x seconds if it's dirty, or only write it once it's done dragging, but that would involve quite a bit more code

chilly surge
#

Done dragging is a good idea yeah. IO is slow.

hidden locust
#

No convenient "done dragging" event I can hook into from the looks of it, though πŸ˜’

#

although the underlying implementation seems to use a unity ui slider... maybe there's something I can expose...

#

Looks like I have to extend that functionality manually, or add a separate monobehaviour to the slider gameobject to listen for onpointerup

lean sail
glass linden
#

I guys, I have a project where I need my program to react to words I say, I found some tutorial on the internet but I can't change the words. Anyone know how to do it ?

https://www.youtube.com/watch?v=nqIJrPswBPE

I try this tuto but when a change the word it doesn't work, it's like it isn't in the code where you have to change what word you have to say

TUTORIAL
https://lightbuzz.com/speech-recognition-unity-update/

SOURCE CODE
https://github.com/lightbuzz/speech-recognition-unity

Learn how to develop a game with speech/voice recognition capabilities using Unity3D and C#. Supports Voice Commands and Dictation.

Brought to you by LightBuzz.

β–Ά Play video
rigid island
glass linden
#

yes, when a change "up" for somthing else it doesnt work and when i said up the bee stop
I think the code change the action of the word not the word them self

rigid island
#

You should probably share the code cause this aint helping understanding the issue

hidden locust
faint hornet
#

Hey everyone, i am wondering how to convert a vector2 input to a rotation value between 0-360 degrees;

for example i am using the new input system and i want to take the left stick from a gamepad and convert the angle of the stick to the players looking direction in a 2d environment.

any help?

leaden ice
#

player.transform.right = inputDirection;

#

(or .up if your sprite is arranged that way)

neon zinc
#

Is there any easy way to set a param of a function in the Unity inspector from a Dropdown o something similar?
for example, I have this method : public void IngredientSelected(Ingredient ingredient){} where Ingredient is a public enum with some ingredients :
public enum Ingredient {
Bread,
Cookie,
Tomatoe,
Pepper,
Strawberry,
Onion,
Lettuce,
Octopus,
Fish,
Water,
Beer,
Coffee
}
I don't want to make a wrapped method (like this public void SelectBread() {
IngredientSelected(Ingredient.Bread);
}) that call IngredientSelected because I have a lot of ingredients, is there any propper way to make this?

leaden ice
leaden ice
#

Simple way to wrap it though:

public Ingredient chosenIngredient;

public void SelectIngredient() {
  IngredientSelected(chosenIngredient);
}```
glass linden
rigid island
neon zinc
leaden ice
#

button on click is a UnityEvent

#

and you can't pick enums in a UnityEvent

neon zinc
leaden ice
#

(put the script on each button)

lean sail
glass linden
rigid island
#

Your script, hirerchy objects etc

glass linden
#

oh ok sorry

rigid island
#

Im not a mind reader, how should I know why it doesnt work on your end by this video only

#

if it works for them you missed a step or have obvious error

glass linden
#

you don't understand my probleme, i download the code from the video and it work, but i cant change the word (they dont do that in the video)

#

but ther is my setup

#

I have a gameobject with the main script on it and a image that can move

#

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Windows.Speech;

/// <summary>
/// see here https://lightbuzz.com/speech-recognition-unity/
/// </summary>
public class SpeechRecognitionEngine : MonoBehaviour
{
public string[] keywords = new string[] { "up", "down", "left", "right" };
public ConfidenceLevel confidence = ConfidenceLevel.Medium;
public float speed = 1;

public Text results;
public Image target;

protected PhraseRecognizer recognizer;
protected string word = "right";

private void Start()
{
    if (keywords != null)
    {
        recognizer = new KeywordRecognizer(keywords, confidence);
        recognizer.OnPhraseRecognized += Recognizer_OnPhraseRecognized;
        recognizer.Start();
        Debug.Log( recognizer.IsRunning );
    }

    foreach (var device in Microphone.devices)
    {
        Debug.Log("Name: " + device);
    }
}

private void Recognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
    word = args.text;
    results.text = "You said: <b>" + word + "</b>";
}

private void Update()
{
    var x = target.transform.position.x;
    var y = target.transform.position.y;

    switch (word)
    {
        case "up":
            y += speed;
            break;
        case "down":
            y -= speed;
            break;
        case "left":
            x -= speed;
            break;
        case "right":
            x += speed;
            break;
    }

    target.transform.position = new Vector3(x, y, 0);
}

private void OnApplicationQuit()
{
    if (recognizer != null && recognizer.IsRunning)
    {
        recognizer.OnPhraseRecognized -= Recognizer_OnPhraseRecognized;
        recognizer.Stop();
    }
}

}

Learn how to develop speech (voice) recognition applications in Unity3D. Source code and step-by-step tutorial by Michael Moiropoulos, LightBuzz.

somber nacelle
#

!code

tawny elkBOT
dark tide
#

Procedural animation help

rigid island
#

also yes post code properly

neon zinc
leaden ice
#

as I said you need to put this script on each button

#

you should not put it in the level manager script

#

You can call a function from the LevelManager from this script

#

braindead example:

public Ingredient chosenIngredient;

public void SelectIngredient() {
  FindObjectOfType<LevelManager>().IngredientSelected(chosenIngredient);
}```
#

But that will be pretty slow - I recommend a better way to get the reference. This is for illustration purposes

glass linden
rigid island
leaden ice
glass linden
#

i change up by cat and when i say cat the bee juste stop

rigid island
#

what does this print
results.text = "You said: <b>" + word + "</b>";

lean sail
#

did you look to see what they are set to in inspector?

rigid island
#

oh yeah this is public..

#

probably need to change words in the inspector

#

new string[] { "cat", "down", "left", "right" };

this will not run again, once it was serialized with previous info

#

only a Reset would fix it

leaden ice
#

(another casualty of unecessarily serialized fields)

neon zinc
# leaden ice in the inspector

Thank you for your patience. I didn't quite understand it because when I put Ingredient as a parameter of a function the dropdown didn't appear, I thought that putting it as an attribute of the class wouldn't appear in the Inspector either.

glass linden
#

There was a drop-down menu that I hadn't seen...

#

That you guys

lean sail
#

Honestly some simple debugging shouldve told you this, like debugging what was said, or what the contents of the array was

faint hornet
leaden ice
#

(speed is in degrees per second. 50 is a good starting point)

hexed oak
#

does RotateTowards offer a parameter that guarantees a direction? I've had issues in the past where I wanted something to rotate clockwise and it rotated counter clockwise instead because it was a shorter distance

leaden ice
#

What do you mean by "guarantees a direction"?

leaden ice
hidden locust
#

So I have a monobehaviour attached to a gameobject that has a unity UI Slider

#

I created a new monobehaviour that implements IEndDragHandler and attached it to the same gameobject but it is not receiving the event

#

Super basic. I add this script to a gameobject with a slider

#

Is it because the slider script itself needs to implement these interfaces?

#

Ah... maybe the issue is I was not actually adding it to the same gameobject as the slider itself... silly mistake. Re-testing now.

#

Yup, that was the issue. πŸ€¦β€β™‚οΈ

faint hornet
#

can someone help me figure out why this is not working. documentation isn't clear.
here are the values i want to change on the particle system with code.

i want to change the orbitalX vector3 in unpdate method

here is my code not working:

var starMain = psStars.velocityOverLifetime.orbitalX;
    starMain.constant = isMoving ? -inputManager.moveInput.x : 0f;```
rigid island
leaden ice
#

Isn't it a struct?

#

structs are not reference types

#

you likely need to do psStars.velocityOverLifetime.orbitalX = starMain; at the end

rigid island
#

yeah VelocityOverLifetimeModule is struct apparently thats the type

leaden ice
#

actually this is probably wht you need:

VelocityOverLifetimeModule vol = psStars.velocityOverLifetime;
var orbX = vol.orbitalX;
orbX.constant = whatever;
vol.orbitalX = orbX;```
#

(the PS module structs are weird and themselves don't need to be copied back)

rigid island
split furnace
#

I finally figured out the issues with explosion collision. first thing was rewriting the code to act like a vision cone to check if the target is behind a wall, then make sure I typed dstToTarget instead of dirToTarget (misspelling mistake :P), finally I added a offset to point the raycast to the center of the target instead of their pivot point in the ground.

faint hornet
#

i have a projectile that shoots at a specific velocity. but i want that volocity to inherit the velocity of the player. do i just add it? it doesn't seem correct

vagrant blade
#

Yes

deft pilot
faint hornet
merry stream
#

any suggestions how to manage audio/font so that all scripts can easily access it and it is able to be changed from one location. IE a UI click sound that would have to be changed on many different objects? right now I just have an enum for sound type and a dictionary relating them on my audio manager. Is this good enough? For font, I have no idea how to do it.

faint hornet
#

i have a question about performance.

is it cheaper to have a hundered enemies hold a reference to a prefab, or hold a reference to a prefab manager that is holding the reference?

#

or does it not matter

merry stream
#

it doesnt matter and the second option sounds horrible

faint hornet
merry stream
#

avoid "managers" imo

#

only things that ive found a need to have a manager "singleton" was an audio system and save system

merry stream
#

it creates unneeded dependencies

#

try to make systems that work on their own

#

a prefab that is held in your project files already holds the reference for you

#

there is 0 need to make a gameobject hold it as well

craggy veldt
#

I don't get it, I mean they're managers πŸ˜…

merry stream
#

what part don't you get?

#

maybe i was vague, i mean manager singletons that create dependencies between systems, managers that manager their own systems are not what i was talking about

#

just my own philosophy

rigid island
#

you can just dependency inject down the hierarchy of managers.. they dont all need to be singletons

spring creek
merry stream
#

im curious, where would one ever be used

latent latch
#

prefabs are for chumps. It's all about having a bazillion SOs and a handful of prefabs

merry stream
#

thats what I do tbh

#

lol

spring creek
merry stream
#

yea

#

prefab manager seems strange to me

#

idk tho

spring creek
#

Ah. I use it a lot honestly. I do mostly strategy and rts games. So creating a single manager that handles unlocked and available buildings is useful.

#

In infinite runners you could do the chunks

#

In fps's you could have the ammo and other drops

#

Enemies of course

merry stream
#

hm, i guess I avoid most of that using SO's

#

i see the use cases tho

#

just depends on which workflow u go with

latent latch
#

most prefab managers I use are usually just pooling and those are specific to that prefab type

spring creek
merry stream
spring creek
#

I prefer to avoid having a bunch of assets.
I also avoid precise prefabs. I generally have a single enemy prefab that I build custom versions of from my managers

#

I just really really dislike the way so's are handled though

merry stream
#

I have a single enemy prefab that is then changed when instantiated by an SO that it holds

#

you prefer to just build the enemies through code?

spring creek
#

Yep.

#

Pocos and mbs

merry stream
#

i see, that seems pretty good as well

deft pilot
#

whats an SO

merry stream
#

so you would have some EnemyBuilder and then all the enemies stats/specs laid out in code

#

and it would pull from that when the prefab is instantiated

spring creek
deft pilot
#

ahh okay thanks

spring creek
latent latch
#

I like SOs because I don't have to worry about overriding the damn prefab instances all the time

merry stream
#

lol

latent latch
#

and you do run into version problems with people because of that, so I'm not exactly sure how teams work with that

spring creek
#

You can certainly read up to see about my workflow

deft pilot
#

mb was backreading about the topic

spring creek
#

I prefer to do just about everything I can through my IDE.
I've mostly moved to Bevy, which doesn't even have an editor, haha, so it wasn't much different

Plus that way I can make changes from my phone via github lol

merry stream
#

I guess i do something similar with my item stats

#

i just hold a bunch of dictionaries with their tiers, weights, rolls, etc

#

and then lookup when needed

#

doing it using SO's would be horrible

deft pilot
#

i only really use SO's only for storing stats of an object i have in the game, per se i have a weapon object, i can just assign stats to it using the so, but thats pretty much it

spring creek
deft pilot
#

especially like an inventory system its super handy

merry stream
#

yeah i use them for my inventory heavily

#

though they arent necessary, just super nice

deft pilot
#

you just pass that SO data into corresponding function and ur pretty much halfway done xd

faint hornet
#

question:

how do i add velocity to a projectile when the player is walking the same direction as shooting?

spring creek
#

Should the bullet move FASTER if you shoot in the direction the player is moving?

#

Or you want to avoid that?

faint hornet
# spring creek Can you explain more clearly what you want

i want a bullet to come out of a gun the same always.. but if the player is moving towards the shooting trajectory, i want to add the players movement to the projectile, if im walking backwards and shoot opposite direction, the bullet should travel slower

deft pilot
#

its dependent on the movement of the player

latent latch
#

thenjust append the velocity

faint hornet
spring creek
faint hornet
merry stream
#

multiply the velocity by the magnitude of your player's velocity?

faint hornet
spring creek
#

I assume the bullet is FASTER than the player, right?

#

If so, then it will work

merry stream
#

well you would have to scale the velocity as well since if the player is moving faster, it could mess up the velocity while moving backward

faint hornet
# spring creek Yes it does

this is my code that doesn't work

Vector3 vel = Vector2.up * Time.deltaTime * bulletInfo.velocity;
    vel += bulletInfo.playerVelocity;
    transform.Translate(vel);
merry stream
spring creek
#

That is translate

#

So that changes a lot

#

I thought you were talking about rigidbody velocity

#

What is bulletInfo?

faint hornet
#

i dont want to use rigidbodies, its too intensive for performance with a bullet hell.

merry stream
#

it really isn't

faint hornet
latent latch
#

how are you detecting collison then

merry stream
#

you probably set it up wrong since I thought that in the past as well

#

but i fixed my issues with them and the performance is great

faint hornet
latent latch
#

it may run into issues where you bullets may not register

spring creek
#

So, no OnCollisionEnter or OnTriggerEnter
That is what mao was wondering I believe

#

You're using physics queries?

faint hornet
#

not for bullets

merry stream
#

you should use rigid bodies

latent latch
#

kinematic rigidbodies

faint hornet
#

ok i'll try that i guess

latent latch
#

it's physic queries vs OnTriggerEnter

#

OnTrigger is more performant if you are checking every fixed frame

#

Overlap is more performant if you are doing it every other num frame

faint hornet
merry stream
#

yes, use a circle collider for best performance

#

if it really matters that much

faint hornet
#

i am

merry stream
#

and set up your collision matrix to reduce unneeded collision checks

faint hornet
#

so my character is using a character controller and doesnt allow a rigibody at the same time

merry stream
#

thats fine for the character

#

but use rbs for the bullets

faint hornet
# merry stream but use rbs for the bullets

so then i just pass the charactercontroller velocity to the bullet. then i dont use deltatime? use fixed update and literally just append player velocity to bullet velocity * speed?

latent latch
#

rb has its own methods

deft pilot
#

rbs will make your life pretty much easier when it comes to dealing things like physics or velocity

merry stream
#

wait i dont believe just adding the velocity would work when moving backward

#

that will cause the bullet to travel backward

latent latch
#

I was thinking maybe you can just query overlap around your character and then you can just use colliders on the bullets themselves. The only problem with this that you lose out on interpolation checking, so if the projectiles are faster than the radius of which you check, then they can pass the player without hitting

#

rb has its own methods of continuous interpolation checks which is the larger reason of using it

#

as long as you use the rb methods to move

merry stream
spring creek
#

Ah, was about to write more, but mao got it

merry stream
#

if the player is moving faster in the opposite direction

#

adding the players velocity would switch the direction of the bullets

merry stream
#

ah okay

#

though adding velocity will make the bullets travel in a slight sideways direction

spring creek
#

But yeah, that is an important consideration

merry stream
#

if your player is moving perpendicular to the bullets

faint hornet
#

here is my code

public struct BulletInfo
{
  public float halflife;
  public float velocity;
  public float damage;
  public Vector3 playerVelocity;
}
public class Bullet : MonoBehaviour
{
  public BulletInfo bulletInfo;
  float elapsedTime = 0f;

  Rigidbody2D rb;

  private void Awake()
  {
    rb = GetComponent<Rigidbody2D>();
  }
  private void Update()
  {
    elapsedTime += Time.deltaTime;
    if (elapsedTime >= bulletInfo.halflife)
    {
      Destroy(gameObject);
    }

  }
  private void FixedUpdate()
  {
    Vector3 vel = Vector2.up * bulletInfo.velocity;
    vel += bulletInfo.playerVelocity;
    rb.MovePosition(vel);
  }

  private void OnCollisionEnter2D(Collision2D other)
  {
    if (other.gameObject.GetComponent<Enemy>())
    {
      other.gameObject.GetComponent<Enemy>().Damage(bulletInfo.damage);
      FindObjectOfType<SoundManager>().PlaySound();
      Destroy(gameObject);
    }
  }
}
latent latch
#

if you can store the speed you can just apply the speed to the forward direction

faint hornet
#

don't mind the bad structure. i literally just started this project today and will clean it up when i move on to the next thing

merry stream
#

if a rigidbody has any velocity, it is moving already

#

so you just set the velocity once

#

you don't need to move posiiton or anything

faint hornet
#

oh wow ok

merry stream
#

so when you set the velocity, you would also take into account the player's velocity

latent latch
#

deltatime bullets is bad without a lot of extra work you probably dont want to do

merry stream
#

but i believe adding the velocity will not work correctly

leaden ice
#

That code also makes no sense

#

You're plugging a velocity into MovePosition

#

Which wants a position

merry stream
#

velocity is a vector

leaden ice
#

So what?

merry stream
#

you set velocity to any vector, it will move in that direction

#

im just stating that, not responding to you

leaden ice
#

MovePosition moves to a specific position you give it

merry stream
#

i dont think dillan understands that since the moveposition stuff

leaden ice
#

Velocity doesn't belong as the parameter

merry stream
#

the bullet shouldnt even think about its own velocity really

#

your "gun" should be doing that

faint hornet
# leaden ice That code also makes no sense

ok what about this?

public struct BulletInfo
{
  public float halflife;
  public float velocity;
  public float damage;
  public Vector3 playerVelocity;
}
public class Bullet : MonoBehaviour
{
  public BulletInfo bulletInfo;
  float elapsedTime = 0f;

  Rigidbody2D rb;

  private void Awake()
  {
    rb = GetComponent<Rigidbody2D>();
  }
  private void Update()
  {
    elapsedTime += Time.deltaTime;
    if (elapsedTime >= bulletInfo.halflife)
    {
      Destroy(gameObject);
    }

  }
  private void OnEnable()
  {
    Vector3 vel = Vector2.up * bulletInfo.velocity;
    vel += bulletInfo.playerVelocity;
    rb.velocity = vel;
  }

  private void OnCollisionEnter2D(Collision2D other)
  {
    if (other.gameObject.GetComponent<Enemy>())
    {
      other.gameObject.GetComponent<Enemy>().Damage(bulletInfo.damage);
      FindObjectOfType<SoundManager>().PlaySound();
      Destroy(gameObject);
    }
  }
}

this code is making the bullet go upwards always no matter the direction i am and the forward vectors

latent latch
#

well, you can moveposition using the transform's location + the velocity

faint hornet
merry stream
#

dillan send the code where you instantiate your bullets

latent latch
#

rb.MovePosition(transform.position + delta * speed * direction)

faint hornet
#

ok

faint hornet
# merry stream dillan send the code where you instantiate your bullets
public void FireShot()
  {
    Bullet bullet = Instantiate(bulletPrefab, bulletContainer);
    bullet.transform.position = transform.position;
    bullet.transform.up = inputManager.lookInput;
    bullet.transform.Translate(Vector2.up * .65f);
    bullet.bulletInfo = bulletInfo;
    bullet.gameObject.SetActive(true);

  }

this code is not adding the players velocity yet. i'm just trying to get it back to working properly

merry stream
#

you should set the velocity there

latent latch
merry stream
#

also you dont need to set the and all of that, you can do that all in instantiate

faint hornet
merry stream
#

well that is the way it will start working

#

you just set the velocity there

faint hornet
merry stream
#

your bullet doesnt need to know about the player since the player already knows about the player

#

which i assume the gun is attached to

#

you avoid having to pass it in through bullet info

#

it should work, just makes a bit less sense

#
Vector3 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (Vector2)((worldMousePos - caster.transform.position));
direction.Normalize();

Projectile projectile =
Instantiate(projectilePrefab, caster.transform.position + (Vector3)(direction * 0.5f), Quaternion.LookRotation(Vector3.forward, direction));
#

this is how I do it

#

then set the velocity to direction

faint hornet
merry stream
#

yes

#

read up on quaternions if u wanna know why, i dont even fully understand them tbh

errant bolt
#

So, I figured out how to add my anchor data to custom image elements and embed them in my graph nodes, but I ran into an error specifically with asset selection menu that would normally appear when clicking on an object field like in this picture. It throws a null reference only when clicked, but you can drag and drop images in as normal and it seems to work correctly.

Does anyone know if getting that asset selection menu to appear is a property of using manipulators?

calm talon
#

how do I allow a variable to be seen in inspector, but to not allow its value to be changed (from the inspector GUI)?

rigid island
#

you can also use Debug mode to view private vars

calm talon
calm talon
rigid island
#

ya pretty fun stuff

faint hornet
# merry stream yes

do you know why the enemies in my game are looking kinda choppy almost low framerate? should i remove riggid bodies from enemies? the enemies stack up quite alot

latent latch
#

mess around with it

#

try kinematic, ect

#

but otherwise if you don't need it (dont care about knocking back enemies) you can probably ignore it

#

there's a lot of things you can try, but most falls into how you're doing a lot of the pathfinding

faint hornet
#

it doesnt make sence though. i only have like 25 small enemies on screen with nothing but movement and it's choppy

latent latch
#

then that's somethign to profile yourself

faint hornet
# latent latch then that's somethign to profile yourself

this is the only code i have on enemies

private void Update()
  {
    Vector3 direction = (player.position - transform.position).normalized;
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    rb.rotation = angle;
    moveDirection = direction;
  }

  private void FixedUpdate()
  {
    if (player)
    {
      rb.velocity = new Vector2(moveDirection.x, moveDirection.y) * speed;
    }
  }
latent latch
#

should mostly be doing this stuff in fixedupdate when using rb

latent latch
#

oh right that's probably it

#

should consider MoveRotation though as instantly changing the angle like that isn't lerp'd

faint hornet
#

ok

faint hornet
merry stream
#

anyone who has used NaughtyAttributes know if it's possible to hideif OR between a bool and an enum

#

or use multiple hideifs/showifs

craggy veldt
#

that can be easily done with uitoolkit (custom editor)

#

oh didnt see it's about naughtyattributes

latent latch
#

otherwise you can use multiple flags
[ShowIf(EConditionOperator.And, "flag0", "flag1")]

#
public enum EnumType
{
  entry1,
  entry2,
  entry3,
}

EnumType enum1 = EnumType.entry1;
EnumType enum2 = EnumType.entry3;

[ShowIf("EnumCheck")]
public float myFloat;

public bool EnumCheck() 
{ 
  return enum1 == EnumType.entry1 && enum2 == EnumType.entry3; 
}
merry stream
#

thanks

latent latch
#

oh, substitute one check with a bool as I misread that

plain ibex
#

it gives an error for balletScript.balletSpawnpoint = new Vector3(balletScript.transform.position.x,balletScript.transform.position.y,0f); line

#

NullReferenceException

#

but how ??

neat forge
#

You don't assign balletScript anyhwere, so probably that

quartz folio
#

None of this involves assigning to the variable balletScript on SliderController

plain ibex
#

fixed thanks πŸ‘

merry stream
#

any suggestions how to manage audio/font so that all scripts can easily access it and it is able to be changed from one location. IE a UI click sound that would have to be changed on many different objects? right now I just have an enum for sound type and a dictionary relating them on my audio manager. Is this good enough? For font, I have no idea how to do it.

cold parrot
# merry stream any suggestions how to manage audio/font so that all scripts can easily access i...

Make a audio-player component that has a method (or parameter on a single method) for each sound you want to play and reference that component in all your sound-triggering components. Alternatively have the trigger component find the audio-player through a service locator (pattern), inject it on instantiation or, if you want to go down the route of bad architecture, make that audio-player component a singleton.

merry stream
cold parrot
#

Another way would be to only have a centralized audio-clip provider (similar to the player above) that returns only a clip for a given sound-key and you play that locally. This could be a scriptable object.

merry stream
#

ah so I could just plug that SO into everything that would play a sound

merry stream
#

thank you

#

any suggestion for the font?

cold parrot
#

same

#

you just have to make a script that assigns the font n awake/start to the text component

merry stream
#

kk thanks

merry stream
latent latch
#

entity.stats vs gameManager.entity.stats

#

make everything a singleton vs make one thing a singleton

merry stream
#

seems like a lot of hassle for not much gain since I only have a Save and Audio singleton

#

and nothing really depends on them

latent latch
#

yeah usually not a big deal for single use type managers

#

I find it cleaner though just to reference by some super manager

merry stream
#

yeah i made my game in a way that avoids most of that, nothing communciates through singletons

#

true

#

all my singletons are basically read only or have some public functions that do something that is not needed by any class ie play audio

#

probably can get rid of them in general tbh

#

so i guess the big benefit of a service locator is when doing additive scene loading

#

so things can essentially talk through different scenes

cold parrot
# merry stream so i guess the big benefit of a service locator is when doing additive scene loa...

It’s the best compromise between bad architecture and convenience for discovering the β€˜manager’ of a dynamically spawned component in small/solo teams. Mostly because it can be the only singleton and you can use it in a way that you don’t create coupling all over the place and retain some control over what the locator returns for a given type, which helps a lot with testing.

#

It’s more work to write a singleton than it is to use a simple service locator imo. I constrain my use of the pattern to one cached call per lifecycle object and only if static references are impossible. Also the registered services are immutable after scene/level startup and all services register as interfaces.

elder flax
#

Ok i'm asking here since this seems kinda simple. I have a list of 'cities', and a total population. I want to distribute the total population between the cities, not evenly. I have a texture2d that i want to act as a heatmap, to give weighting to some cities over others. I can't figure out what to do to assign each cities population correctly as i loop through them though

plain ibex
#

i have a weird problem. i'm using instantiate for bullet system and problem is when i use slider control to move right, it shots clone bullet with original bullet. but this problem happens only when i move right

somber nacelle
#

don't have the bullet object actually in the scene, use a prefab

plain ibex
#
public void OnSliderValueChanged()
    {
        aticiUcu.transform.rotation = Quaternion.Euler(0f,0f,-sliderComp.value);
        balletScript.balletSpawnpoint = new Vector3(balletScript.transform.position.x,balletScript.transform.position.y,0f);
    }```
somber nacelle
#

the issue is likely that the new bullet is colliding with the "original" when rotated in that direction

plain ibex
#

yea im using prefab but i forgot removing original object from hierarchy

#

πŸ‘ thanks

dawn nebula
#

You think needing a 2 way dictionary is a sign of bad design?

#

That or just 2 dictionaries.

plain ibex
#

@somber nacelle i removed it from scene but now it doesnt let me assign gameobject that i marked

#

in prefab

#

i cant assign it

somber nacelle
#

prefabs cannot reference in-scene objects. pass the reference when you instantiate it

dawn nebula
#

I have objects that I want to ID. I have a manger class that allows me to "register" objects to be ID'd.

#

I'm finding that I want to be able to both ask the manager "Hey I have this ID, can I have the object" and "I have this object, does it have an ID?"
I can solve this by usng 2 dictionaries (Object to ID and ID to Object). Do you think this is bad practice?

slow shoal
#

Hello friends

plain ibex
#

thanks

somber nacelle
slow shoal
#

Oh alright

#

my bad

vestal crest
#

hi, how would you build your architecture if your game has a multiple of game types such as 5v5, battle royale etc. and they can be playable as team vs team or free for all or bot of them

dawn nebula
#

Cause in a team based game you do need to make sure their are specific interactions against allies.

#

While in something like a free for all, everything is technically an "enemy".

vestal crest
#

yeah but game tpye needs to know if its a team or free for all, for example capture zone game needs to know all zones has captured by the same team

merry stream
#

hey lazy i finally got that ability system I was working on months back in a working state lol

#

pretty proud of it

#

i appreciate the help u gave

dawn nebula
dawn nebula
#

Team size, number of teams, etc.

#

I mean technically in a free for all everyone is on their own team πŸ˜›

dawn nebula
#

I could have sworn there was some way to return a list as ReadOnly without creating a new object.

reef imp
#

Is this the right place to ask a question about GPS using Unity - I'm trying to make it work on my phone but the LocationService is hanging on Initializing

#

I got perms enabled, tried both fine and coarse perms and changed the LocationService parameters

#

I've tried it using handheld as well as an emulator and I'm still getting it to time out

#

(The emulator timed out with prebaked GPX data)

#
    IEnumerator Start()
    {
        if (!Input.location.isEnabledByUser)
        {
            statusText.text = "Location service is not enabled. Please enable it in settings.";
            yield break;
        }

        statusText.text = "Initializing location services...";
        yield return new WaitForSeconds(3);
        UnityEngine.Input.location.Start(500f, 500f);


        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
        {
            yield return new WaitForSeconds(1);
            statusText.text =  (20 - maxWait) + " seconds...";
            Vibrate();
            maxWait--;
        }

        if (maxWait < 1)
        {
            statusText.text = "Timed out. Try moving to an open area or check your GPS settings.";
            yield break;
        }

        if (Input.location.status == LocationServiceStatus.Failed)
        {
            statusText.text = "Unable to determine device location. Please try again later.";
            yield break;
        }
        else
        {
            statusText.text = "Location services initialized.";
            StartCoroutine(CheckLocationRoutine());
        }

    }```
#

Specifically

somber nacelle
reef imp
#

okok

gilded vapor
#

uh i have a problem error c#

leaden ice
somber nacelle
tawny elkBOT
bleak thorn
somber nacelle
#

!collab πŸ‘‡

tawny elkBOT
somber nacelle
#

and don't crosspost

woeful narwhal
#

for the unity timeline, is there a better way to trigger functions outside of the signal emmitors? the signal emmitors are pretty uncustomisable and will clunk up my project with a bunch of assets

cold parrot
gilded vapor
somber nacelle
#

okay so get vs code configured

woeful narwhal
gilded vapor
somber nacelle
#

open your code?

#

i really shouldn't have to hold your hand through something so simple

surreal cloak
#

out of no where this came out

#

did i do smth wrong

simple egret
surreal cloak
deep path
#

do you make it ?
anyway it's not using chatGPT

soft shard
# dawn nebula I'm finding that I want to be able to both ask the manager "Hey I have this ID, ...

I would just make 2 functions to do a lookup on 1 dictionary, I find using Linq the easiest way of doing this, for example FirstOrDefault will return the first object that matches your ID, if your ID does not match any object, then default is returned instead, so you can treat it as a "null condition" - and vice versa, if the object is null, you can return -1 for the ID and handle that as a "null condition" as well, and if the object is not null, you can return the objects ID property - with Linq, theres a bit of GC cost, with a copy of your dictionary theres a memory cost, and from what your describing I dont think you would absolutely need the copy to do a "reverse lookup" (alternative to Linq, you could also use a foreach loop and check each element for a matching ID or use HasKey if your ID is used as a key, or Contains/Exists otherwise)

soft shard
# vestal crest hi, how would you build your architecture if your game has a multiple of game ty...

For my game, I used a SO to describe the game mode and data thats consistent across all game modes (player count, team sizes, match time, etc), then a manager in its own scene that takes the SO and creates a interface of IWinCondition, basically acting as the game rules, that manager subscribes to the servers tick rate instead of Update to check every server second if the win condition has been met - I can then make specific game mode scripts that inherit that interface for example TDM:IWinCondition can decide if one team has been eliminated, or if the teams score is >= whatever the SO says, or if the match time has ran out (if that mode has a time limit), or if all 5 capture zones are owned by 1 team ID, etc - I can also do the same extension with the SO if for example TDM also needs to specify a number of capture zones or kill count to win, I can have a TDMSO : GameModeSO - my approach uses a manager, through inheritance can become a game mode, defined by a SO, through a interface, but not the only approach, with any approach you take, youll want to make sure you have a way to execute game mode-specific logic and rules, I chose a interface, since TDM can also be a Mono and replace the standard manager in the match or handle custom games if I wanted to

vapid lynx
#

i had a qusetion

#

i have a pathfinding algorithm that i coded

#

that returns a list of vector3 points

#

and i want to use those points to create a road mesh and am lost as to how i wouuld do this

knotty sun
leaden ice
vapid lynx
vapid lynx
leaden ice
#

which is just a fancy way of saying "creating a mesh with your code"

arctic plume
#

Does the Resources folder not work for builds of Unity games?
I'm trying to run a build of my game and it can't seem to access anything from the resources folder

leaden ice
#

show more details of your issue

cosmic rain
#

I bet they're trying to add files to a Resources folder in the build and load them

delicate flax
arctic plume
#

And then this is my folder:

somber nacelle
#

and what is the filepath

arctic plume
cosmic rain
#

probably need the extension too

leaden ice
#

you don't

#

no extension

arctic plume
#

No, Resources doesn't work with extension

somber nacelle
#

have you checked the player logs to see if there are any errors reported

leaden ice
#

I would expect to see:
"Looking for file: some/path"
"No audio clip found"

for a clip that actually exists

arctic plume
#

Where would I find the logs for builds?

leaden ice
#

in the log file

#

make sure it's a dev build

somber nacelle
#

!logs

tawny elkBOT
#
πŸ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

leaden ice
#

You want the "player logs"

arctic plume
#

There doesn't seem to be any Editor.log in that folder

somber nacelle
#

you're looking for the player logs not the editor logs

cosmic rain
#

You can also attach the debugger to the game process to be able to both see the console and step through the code.

arctic plume
#

Ahh found the player log now, lemme take a quick look through

#

Ok that's weird, instead my log file appears to be clogged with something breaking at the very beginning

Basically my game has a "Dialogue Menu" of sorts, and the Dialogue Menu gets updated after each person has finished speaking
So I figured there was an issue loading the audio files
But it seems like there's an issue initialising the menu

#

Not sure why that would happen if it doesn't have that issue running from the editor

somber nacelle
#

what's in the updateButtons method

leaden ice
#

that's the typical reason builds break vs the editor

#

but yeah now that you can get at the player log you can start debugging for real!

somber nacelle
#

oop that's a lot of potentially null objects

arctic plume
#

Ok I'm back with a more exact issue, I just don't understand why

vapid lynx
#

does unity 2021 have splines?

#

if not, how can i import them?

somber nacelle
#

it should, you may just need to import it by name if you don't see it in the package manager
com.unity.splines

rocky jackal
#

Why do i get this error ? It a ppeared out of nowhere when i edited a different script and i have no clue what could cause this

arctic plume
#

For some reason it can't find my Json file in the build?

somber nacelle
#

the Assets folder does not exist in a build btw

arctic plume
#

Yeah so I'm gonna have to try redirect that, what path would I put in to read a file so that it will work in an actual build?

somber nacelle
#

you could put it in the resources folder and load it with Resources.Load or you could throw it in StreamingAssets, or you could create the file if it does not exist at your desired path (such as in Application.persistentDataPath) and read it from there if it does

mossy snow
#

if the file is immutable and not something you want the player to have access to, another option is TextAsset and not bother with paths at all

somber nacelle
#

ah yeah, true. i forget that exists

somber nacelle
#

are you sure you're on 2021 πŸ€”
those errors indicate that there is an issue with using a target typed new which is perfectly valid in 2021

somber nacelle
#

2021.1
why

vapid lynx
#

my school project requires me to work with that 😭

#

my teacher was unwilling to let me use a more recent version

#

wait so can i js not use splines

somber nacelle
#

well that's too early to use c# 9 so πŸ€·β€β™‚οΈ

vapid lynx
#

oh

somber nacelle
#

pretty sure even the oldest versions of the splines package require 2021.3

vapid lynx
#

is there any other option that i can use to make a road mesh out of vector 3s

somber nacelle
#

have you googled how to make roads via code?

vapid lynx
#

yeah i tried

mossy snow
arctic plume
fleet otter
#

Hello guys, I have some issues with drag & drop with UIDocuments (during gameplay).

So my problem is the following: I
have a UIDocument that is representing an inventory, I made the inventory window draggable with PointerEvents.
I did the same for items inside items slots. Whenever the item is dragged outside the window of the inventory it starts "teleporting" or acting funky, any idea why that might happen?

main coral
#

Can someone help me with this ?

gray mural
main coral
#

there is no code its from Lozcalized strings something

gray mural
#

Oh, I see

#

Well, I have no idea about this error.

#

When does it even happen?

main coral
#

how can I manually update to 1.5 localized strings ?

earnest meteor
#

Hello everyone. I want make a object rotation and check when my character did a somersault. But i cant realize how to debug degrees in console. Maybe anyone can help?

leaden ice
#

do you want to know if the object is upside down?

#

it's really better not to try to read euler angles to do that

#

gimbal lock is going to kick your ass

earnest meteor
oblique spoke
main coral
#

yea i have updated it

#

now it works

leaden ice
#

euler angles are a bad idea almost always. What you really want is Vector3.SignedAngle

#

this way you can define the axis of rotation you care about and not get killed by gimbal lock

earnest meteor
leaden ice
#

but I'm warning you nothing but sadness lies that way

earnest meteor
earnest meteor
#

not final version.

calm talon
#

If I'm using a rule tile, how may I check which particular tile is going to be placed at a particular cell position (via code)?

spring creek
#

No need to ping me, especially twice πŸ˜‚

Now, one thing I see is that your fps tracking is messed up badly.
You should at LEAST yield return null (not .2 seconds...)

#

Two, is this a kinematic rigidbody

jolly kettle
#

@loud stratus - what are you trying to accomplish with particles? You can sort of go about it either way, so it depends on your use case.

spring creek
#

Then you probably should not be using MovePosition

#

Also, have you used a profiler to actually verify the issue?

#

And in the hierarchy view, what is taking the most time?

brave furnace
#

Quick UI coding question: How do I use a Multiple 2D sprite as background image in my UI Style Sheet?

pine bronze
#

hey, im making an android game but when i compile i get an "Gradle failed to build" error and it says to check the console for more info, but i do not know what these errors mean and i cant find help on google/youtube, can somebody please help me?

dense estuary
#

I am currently trying to make an object rotate at an offset around the player. How can I accomplish this? What I am doing currently: cs void RotateObject() { Vector3 desiredRotation = Vector3.Lerp(rotatingObject.transform.forward, -camera.transform.forward, 1 - Mathf.Pow(smoothing, Time.deltaTime)); rotatingObject.transform.forward = desiredRotation; } void PositionObject() { Vector3 position = camera.transform.localPosition + objectOffset; rotatingObject.transform.localPosition = Vector3.Lerp(rotatingObject.transform.localPosition, position, 1 - Mathf.Pow(smoothing/(Mathf.Pow(1, 100000)), Time.deltaTime)); }

spring creek
#

So open that up and find the actual thing.

That is a LOT of allocation calls too.
Doing yield return new allocates a new thing everything time, but that isn't gonna be all of it

#

Yes... open that

dense estuary
spring creek
#

Editor loop is irrelevant. And nothing useful is showing here.
It is all collapsed

rancid frost
#

if boundsPosition = (0,0,0)
how is it possible for ChunkGridBounds a struct of type BoundsInt, to not contain said position?

#

NVM, it seems for boundsInt, if your point is touching/equal to the MAX bounds, it is not considered inside the bounds

dense estuary
rancid frost
#

you will have to constantly poll camera world position and offset the radar position to it

somber nacelle
#

you can use one of the animation constraint components like the PositionConstraint or ParentConstraint

lethal vigil
#

This is code for my camera for a 2.5 endless runner for mobile,

using UnityEngine;

public class TrackingCam : MonoBehaviour
{
    public float followSpeed = 6f;
    public float smoothingFactor = 0.1f;

    private Vector3 velocity = Vector3.zero;

void FixedUpdate()
{
    Vector3 targetPosition = transform.position + Vector3.right * Time.deltaTime * followSpeed;
    transform.position = Vector3.Lerp(transform.position, targetPosition, smoothingFactor);
}
}

The issue is when the follow speed is 6 which is the pace i want my game to be the backgrund and coins all become blurry with motion, so is there a way i can keep the speed but get rid of motion blur

rancid frost
#

I doubt your camera speed* is the issue, sounds like a rendering problem to me

lethal vigil
#

can i use it to get rid of it?

rancid frost
#

that, im not sure

#

what pipeline are u using?

lethal vigil
rancid frost
#

change the update mode on the camera

#

perhaps, you could use Cinmachine vcam

#

doesnt seem like u are using it

lethal vigil
rancid frost
#

fixedupdate is ur problem

#

dont run ur code in there

#

try running it in update and change the frame rate

lethal vigil
merry stream
rancid frost
merry stream
#

this calculates the damage recieved based on elemental resistance, dodge chance, and crit chance

#

im only looking for optimizations since the code works fine

#

is list<keyvaluepair> the best choice here?

#

etc

#

damagetype is just an enum with types such as physical, fire, etc

rancid frost
#
Pre-optimization is the root of all evil
#

if it works fine, move on to greener pastures my friend

merry stream
#

i like to optimize, im just asking if theres anything glaringly wrong

rancid frost
#

ok, let me take a look

merry stream
#

since this will be called 100s of times a second

modern creek
#

why will this be called 100s of times a second instead of once when damage is emitted/contacted? .. that's going to be infinitely more productive than trying to optimize this chunk of code

merry stream
modern creek
#

if there are 100s of enemies on screen and this method is called once when the user casts a spell or whatever, that's insignificant and you should move on

#

basically start optimizing when you have a hot path called >1k times per frame or second

merry stream
#

yes I understand, i want to use it as a learning opportunity for the cases to use list<keyvaluepair> over dictionary

#

im asking a simple question, i understand its insignificant

rancid frost
#

You could prob put all of this in one loop

modern creek
#

buuuuuuuuut.. what i see: 1) don't allocate the out list every frame, cache it and reusue it 2) the "helpers.percentchace.current" is smelly code, it doesn't seem like it should be a bool based on the naming convention, and has very little in the way of guard clauses (high bug surface here - array index out of bounds, NRE, etc); 3) foreaching over ratios to allocate a new KVP is also wasteful - don't allocate (new) in hotpath if you can avoid it.. 4) you foreach again in final damages with a bunch of fragile calls (no guard clauses, you're gonna have array out of bounds and NREs and have a heck of a time debugging it later), and you also new in the second foreach..

merry stream
#

Helpers.PercentChance is called with the param that has .current

#

i think you misread it

modern creek
# merry stream im asking a simple question, i understand its insignificant

you asked a simple question but the simple answer wasn't what you expected - it was "don't optimize this but instead optimize the code that's calling this".. and again, optimizing early is irrelevant until you have some data that indicates that the hotpath is problematic.. i'd wager that even as clunky as this code is written it's only taking a few nanoseconds per frame and ultimately not worth the attention

merry stream
#

i appreciate it though

modern creek
#

i understand the code - and why is it .Current and not .IsCurrent or .IsActive or something else that indicates it's a bool? target.stats.current reads in english as "this is the dodge stats current value" not "this dodge stat is current/active"

merry stream
#

i am calling the Helpers.PercentChance function passing in the current crit chance value, i believe that makes perfect sense

modern creek
#

language matters - and it's not just for your coworkers (or us), but for you own readability later when you can't figure out why this method is NRE'ing or off-by-1ing

rancid frost
modern creek
#

"PercentChance" is not a verb - methods should be verbs

#

GetPercentChance() or TryCalculatePercentChance() are method names, PercentChance is a property name - again, putting the ()s on it makes it a method (obviously) but readability matters and this is named wrong

merry stream
#

okay, though the "current" refers to the float value associated with that stat

#

isCurrent would make no sense

modern creek
#

Helpers.PercentChance() in this situation is doubly badly named, because it's not a verb, and it doesn't indicate that it returns a bool

merry stream
#

kk, switched it to GetPercentChance

modern creek
#

so why does Helpers.PercentChance() return a bool? it's very difficult to understand your intent from your naming convention, and if we (I) get hung up on trying to understand your intent from poorly named variables it's doubly difficult to assess what you're asking for, which is optimization .. hope that makes sense

merry stream
#

yes, i appreciate the help, all the function does is return Random.Range(0, 100) >= 100 - percent;

#

so if you pass in 60, it will roll a 60% chance

modern creek
#

it shouldn't be GetPercentChance then if it returns a bool - what does it do? IsPercentChancePositive()? or DidDodge()?

merry stream
#

to be true/false

#

maybe "RollChance" would be a better name

modern creek
#

ok then i'd rewrite it to be more clear:

float chanceToDodge = target.Stats[Stat.Dodge];
bool didDodge = Random.Range(0,100) < chanceToDodge;
if (!didDodge)
{
  // do some damage
}
#

see how much easier that is to read and understand? being a good programmer/developer isn't about being clever and trying to jam 100 things on one line, it's making sure that your code is easily readable so that when you need to maintain it a year from now, or when you need to debug a problem with it, it's easy and obvious what the problem is

#

I know it's a little tangential to what you're asking for but .. it's still important and what I would tell a junior who brought this to me to fix

merry stream
#

kk, thank you

modern creek
#

i also don't understand the casting of crit damage to an int and then putting it in a KVP with a float .. but it looks like you have some mage going on here with finalDamages

#

don't use var - you're obscuring your intent.. requiring the reader to find the declaration of finalDamages to figure out what is the purpose of finalDamages.IndexOf() is doing - and also, it's likely that this is a terrible use here.. indexOf needs to iterate the entire list to find it.. instead you should use a dictionary and just reference the item directly by a key

#

(line 21)

merry stream
#

the int/float stuff is left over from when I was undecided on if I wanted damage to be only ints or floats, will fix that

modern creek
#
            foreach (var damage in finalDamages) // iterate final damages
            {
                int critDamage = (int)(damage.Value * (100 + caster.Stats[Stat.CritDamage].Current/100f));
                finalDamages[finalDamages.IndexOf(damage)] = new KeyValuePair<DamageType, float>(damage.Key, critDamage);
                //                        ^^^^^^^ iterate final damages again - for loop within a for loop = O(n^2)
            }
merry stream
#

can you format that a bit

modern creek
#

and again below on lines 27 & 36

merry stream
#

ah i see

#

so indexOf just loops over

#

so it would be better to just make a dictionary instead

#

despite the additional overhead

modern creek
#

if it's a list, yes, which i don't know if finalDamages is until i find out where it's declared (up at the parameters) - ie, don't use var

#

you're not at the point where you have to worry about overhead

#

you're at the point where you have to identify the correct data structure for the application

#

list = do something to everything
dictionary = do something to one item
hashset = check if one thing exists/doesn't

#

start with that

merry stream
#

okay, my thought process was that if I don't need to index into the container a lot, which I wont unless I need to access that specific damage type, IE if a player dies to it to display the damage and the type they died to, I don't need to make a dictionary for it

modern creek
#

i'm not sure what ratios and finaldamages are for your parameters (they're poorly named) but I'm .. guessing? that you have some sort of multiplier for damage types (based on the targets resistances? weaknesses?) and you want to output the final damages for each damage type?

merry stream
#

yes, so a given ability will have a ratio of damage say it does 60% fire and 40% physical

#

and will take the players stats based on that ratio

#

or even 500% physical, etc

modern creek
#

if the target has fixed ratios you don't ... make a list of KVPs, you just use a dictionary:

Dictionary<DamageType, float> damageMultipliersForTarget = ...; // property of target
Dictionary<DamageType, float> damageMultiplierByCaster = ...; // property of caster

public static float GetDamageDone(AbilityCharacter caster, AbilityCharacter target, out Dictionary<DamageType, float> damageDone, out bool didCrit)
{  
  damageDone.Clear(); // requires init outside this method
  didCrit = false;
  float damageDone = 0f;
  foreach (var kvp in damageMultiplierByCaster)
  {
      DamageType type = kvp.Key;
      damageDone += target.damageMultipliersForTarget[type] * rawDamage * caster.damageMultiplierByCaster[type];
  }
  return damageDone;
}
#

something basically like that

#

obviously you have some additional stuff going on, crit chance, etc, but you should just iterate the damage types once

#

this pseudocode also assumes you have well-formed dictionaries, but.. yeah, basically, iterate the damage types once and do the calculations with a dictionary lookup (which is fast - compared to IndexOf() on a list) and then return the sum.. it's also much more readable and understandable and more bug resistant to off-by-one-errors and NREs

#
  // this line can fail in all the ^ places
 var value = new KeyValuePair<DamageType, float>(ratio.Key, (int)(caster.Stats[StatParser.GetDamageTypeToEDamageStat(ratio.Key)].Current * ratio.Value));
//                                                    ^ NRE             ^ NRE  ^AOOB     ^NRE                             ^NRE  ^NRE            ^NRE
#

most of the time? it won't, but it makes a lot of assumptions that all the data is well formed and has no guard clauses to check for problems

merry stream
#

yeah I see why, though in those functions it would be impossible to be missing the value

#

unless null is passed in

modern creek
#

fine but they should still do the guard clause checking

merry stream
#

yeah, i will check for null

modern creek
#

your methods should always assume bad data sent and fail nicely (and preferably log it)

#

because if you do see the log message you instantly know what the problem is and how to fix it

#

and if you don't see the log message, you don't see the problem, and maybe you get weird behaviour that you have to step through code to try to figure out = the worst possible use of time

merry stream
#

true

#

appreciate the advice

modern creek
#

cheers gl

chilly surge
#

Turning on NRT would save you from all those unnecessary null checks and essentially move them to the responsibilities of the compiler instead.

modern creek
#

opinion time/hot take: NRT sucks

chilly surge
#

That's not really hot, C#'s NRT is not great, in particular the language wasn't designed with NRT in mind from the start and has a ton of baggage, and Unity doesn't help that none of the API is NRT aware.

latent latch
#

still not sure of the best practices for null checks. I seem to just stick them into every method that takes some reference just for the heck of it

chilly surge
#

In languages where design takes null into account from the start, it's amazing.

modern creek
#
AbilityCharacter? character = GetCharacter(id); // should this return null? throw an exception? when character w/ id isn't found

If it returns null (successful failure), you still need to check for null. If it throws, you need to try/catch.. more work and uglier code imho

chilly surge
#

That's completely missing the point

#

If GetCharacter returns AbilityCharacter, you don't need to null check; if it returns AbilityCharacter?, yes you need to null check before using it, and the compiler will tell you you need to null check.

modern creek
#

I mean, I've used all the schemes - NRT, response/return types wrapped, and just default nullability without all the NRT nonsense.. I just prefer the non-NRT stuff since it just puts a lot of burden to null check everywhere instead of only "on the border" .. I just don't think it catches enough sneaky NRE to make it worth the hassle

chilly surge
#

Similarly if you have a method void DamageCharacter(Character character), then compiler will prevent you from calling DamageCharacter with possible null, so your DamageCharacter does not need to do null check at all; if you have void DamageCharacter(Character? character), then compiler will force you to do null check.

modern creek
#

again, just opinion.. probably objectively wrong anyway, but you'll never get me to go back to a NRT project voluntarily πŸ˜›

#

(fwiw my server codebase of 100k+ lines is NRT since it is required for the blazor/razor admin tools - i went down kicking and screaming with the addition of NRT)

latent latch
#

Honestly, if I would put more effort into my event systems I could avoid a lot of unnecessary null checking as a null invoke would simply mean that the reference had not be subscribed so there's no fault in the logic there.

chilly surge
modern creek
#

i wrote the code from scratch, myself

chilly surge
#

If you have NRT from the start, it's a completely different experience.

modern creek
#

I still hate it :p

chilly surge
#

Modern languages that don't share the mistake of what C# did, are generally so nice to work with. I've never wasted any time on NRE in those languages, because compiler stops them from even happening at all.

merry stream
chilly surge
#

It's no different from compiler stopping you calling GetCharacterByName(42) because name argument is supposed to be a string.

latent latch
#

Beyond just null checking everywhere, what I do have problems with is duplicate logging warnings. Sometimes I run into a situation where my help method returns the issue, but the method itself that called the issue has a similar log warning.

craggy veldt
signal wadi
#

Hey. I want to make a pause game feature. How can I make it an event and observable? So methods are invoked when the bool changes?

leaden ice
#

Are you asking "how do I use events in C#"?

signal wadi
#

What's the best way of writing it so that it observes changes and invokes on that trigger?

leaden ice
#

Make an OnPaused event

#

invoke it when you pause

signal wadi
#

My idea was setter but properties don't work

leaden ice
#

properties work just fine

#

what's wrong with properties?

signal wadi
#
    public Action<bool> OnGamePaused 
    {
        get { return _isGamePaused; }
    }

    private bool _isGamePaused = false;
leaden ice
#

what

runic nimbus
#

I am having an issue with Vector3.SignedAngle right now.
Here in these two images, the code is working just as intended, attached below

        Vector3 from = transform.right;
        Vector3 to = a.position - transform.position;
        print(Vector3.SignedAngle(from, to, transform.forward));
        Debug.DrawRay(transform.position, from, Color.green);
        Debug.DrawRay(transform.position, to, Color.red);```
#

However, this breaks down when I move the target object a along the z axis? This is specifically the reason I use signed angle, I thought that this would negate any movement on the normal passed into the function
Attached is it not working

leaden ice
signal wadi
#

Incompatible type

leaden ice
ashen yoke
signal wadi
#

GetPaused

ashen yoke
#

thats unrelated

leaden ice
# signal wadi Yea. So they don't work together in this context
public static event Action<bool> OnPauseStateChanged;

private static bool _isPaused = false;
public static bool IsPaused {
  get => _isPaused;
  set {
    if (value == _isPaused) return; // do nothing if we're not changing the value

    _isPaused = value;
    OnPauseStateChanged?.Invoke(value);
  }
}```
For example^
signal wadi
ashen yoke
#

any subscriber to OnPause will receive the bool as argument

#
public event Action<bool> OnPause;

void Start()
{
    //sub to OnPause
    OnPause += HandlePauseStateChange;
}

void HandlePauseStateChange(bool value)
{
    Debug.Log("Pause is: " + value);
}
signal wadi
leaden ice
#

Why else would you ever write a setter?

#

Just use auto-properties at that point.

ashen yoke
#

invoking like that from within setter is standard practice

signal wadi
ashen yoke
#

UniRx had it called ReactiveProperty

leaden ice
signal wadi
#

Thanks both of you

worn bone
#

Hi guys, from reading online, I expected that if I do a Physics2D.raycast from inside a collider, no hit will occur on that collider. But in practice I think its happening. So I wanted to confirm with you. Is it normal that a hit occurs when raycasting from inside a collider?

lean sail
ashen yoke
runic nimbus
#

The bolt rolls around the forward axis, which is why I am using that

runic nimbus
#

It shouldn't matter how far back or forward the hand is, only the X and Y angle of the hand relative to the bolt

merry stream
#

anyone know the function to round a float to the nearest 100th?

leaden ice
merry stream
#

that works too lol

leaden ice
#

Do note, however, that 1/100 and many multiples thereof do not get represented nicely in binary.

#

also if this is to display something in a UI label, you can just use the formatting strings

merry stream
#

ah yes it is

leaden ice
#
myFloat.ToString("F2")```
ashen yoke
#

you can try flattening the to vector so that its z equals to a z
i cant completely picture it but they have to be in the same plane, my guess is that cross product changes if you move one of the direction vectors off the plane

#

@runic nimbus

merry stream
#

thank you

quartz folio
# runic nimbus Well the lines aren't supposed to intersect and rarely will. I'm trying to make ...

Gotcha:
Do not expect the "from" and "to" vectors to be flattened against the Axis when calculating the angle. If the inputs are pointing at all up or down in the plane defined by the axis, you're going to get the "Angle between two 3D vectors" returned. NOT the "Angle between two 3D vectors flattened on a plane".
Workaround: Make sure that you flatten the "from" and "to" vectors against the axis: i.e.

Vector3.SignedAngle(Vector3.ProjectOnPlane(from, Vector3.up), Vector3.ProjectOnPlane(to, Vector3.up), Vector3.up);
#

(A comment made using my extension on the Vector3.SignedAngle docs)

glossy gust
#

!code

tawny elkBOT
glossy gust
#
 Vector3 originPos;
    [SerializeField] bool player2Turn;
    void Start() {
        player2Turn = GameObject.FindGameObjectWithTag("player2turn"); // Finds the gameobject containing the script with the player2turn bool
        if (!player2Turn) {
            origin = GameObject.FindGameObjectWithTag("Origin");
            originPos = origin.transform.position;       
        } else {
            origin = GameObject.FindGameObjectWithTag("Origin");
            originPos = origin.transform.position;
        }
        originPos = origin.transform.position;
        GenerateGrid();
    }
    void GenerateGrid() {
        if (!player2Turn) {
            for (int x = originPos.x; x <= width; x += 3) {
                for (int y = originPos.y; y <= height; y += 3) {               
                    x_Pos = (x / 10f) - 0.15f;
                    y_Pos = (y / 10f) - 0.15f;
                    GameObject spawnedPoint = Instantiate(pointPrefab, new Vector3(x_Pos, y_Pos), Quaternion.identity, pointParent.transform); //Instantiates a new point for each loop cycle
                    spawnedPoint.name = $"Point {x_Pos} {y_Pos}"; //Names each tile according to their tile co-ords
    }}}}

the first parameter in the for loops doesn't work, I want x and y to start from origin position's x and y properties

leaden ice
#

wdym by "doesn't work"?

glossy gust
#

red lines

leaden ice
#

"red lines" is a visual indicator that you have a compile error

glossy gust
#

originPos.x and originPos.y

leaden ice
#

you're supposed to read the error message

glossy gust
#

okay lemme check thanks

worn bone
leaden ice
glossy gust
#

also idk if you care but the issue was originPos.x and y needed to be converted to ints

leaden ice
#

I'm aware

#

I wanted you to discover it yourself

glossy gust
#

fair enough πŸ˜†

spring creek
# glossy gust your right it worked. really need to make that a habit

Do keep in mind that it is not only expected, but an explicit rule to attempt to solve your issue yourself before asking here

Please take your time trying to research your issue BEFORE asking here next time

Not even reading an error before posting is especially egregious. It is exactly that kind of thing that is the reason these rules exist.

worn bone
merry stream
#

how is player debug/logging mode typically handled? is it fine to just create a static debug class that holds toggles for each part that all classes can call some method from

#

for example, i can only turn on "damage" debugging and only recieve those messages

ashen yoke
merry stream
#

thank you

glossy gust
#

Value cannot be null.
Parameter name: _unity_self

#

Ive been getting this issue alot, how can I locate it easily?

spring creek
glossy gust
#

ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <1885898b95cc400580ff334d9d2f9c0f>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)

#

how do I look that up

spring creek
glossy gust
#

im sorry ive never seen an error like that

quartz folio
#

The entire stacktrace is not from your code, so it's not your problem.

#

The only way to prevent it is to try not to do whatever it was that caused it. If you don't know, clear the error and move on

quartz folio
#

Crashing?

glossy gust
#

yeah your right it isnt a code issue

ashen yoke
#

is that the whole stacktrace?

glossy gust
#

it randomly works

#

like rn it worked

#

after exiting unity to come on here then going back to it

quartz folio
#

Crashing would mean that the application closed, and I highly doubt that happened

dreamy niche
#

I have this issue where I cant drag my text box into the spot I have on my script does anyone know how to fix this?

quartz folio
dreamy niche
quartz folio
#

If you're using TMP, that's TMP_Text

spring creek
dreamy niche
#

I've been buggin about that forever

glossy gust
#

whats the term for that

quartz folio
#

I have no idea what " broke out of the play test" means. If you mean it paused, then that's because you have error pause enabled

ashen yoke
#

you may mean you exited PlayMode

glossy gust
#

yeah

glossy gust
merry stream
#

anyone know why this is formatting incorrectly?

cosmic rain
merry stream
#

yea

#

should look like this

cosmic rain
#

Does it actually support color tags?πŸ€”

#

Or any rich text tags at all

merry stream
#

yeah i guess with console enhanced

#

or yeah

cosmic rain
#

Oh, so you're using an asset

merry stream
#

even without it it does

#

yes but rich text still works]

cosmic rain
#

I don't think it supports them by default.

merry stream
#

it does

#

this is the base console

cosmic rain
#

Alright. Maybe reverse engineer that log to see what tags they're using.

merry stream
#

i'm doing it lol

#

no reverse engineering

#

I think it might be an issue with it being multiline?

#

not sure

cosmic rain
cosmic rain
merry stream
#

i'm trying to have it all in one message

#

sec

#

return string.Format("<b><color={0}>[{1}] </color></b> <color={2}>{3}</color>", channelColour, logChannel, priortiyColour, message);

cosmic rain
#

And the one for the not working one?

merry stream
#

thats the general form

cosmic rain
#

In fact it would be better to compare them in the debugger such that you see the final form of the string and escape characters too.

merry stream
#

so the whole string would go in {3}

#

<b><color=cyan>[Combat] </color></b> <color=grey>Player attacks Floating Skull, it has 0 FireResistance and takes 80 damage reduced from 80 damagePlayer attacks Floating Skull, it has 0 IceResistance and takes 39 damage reduced from 39 damagePlayer attacks Floating Skull, it has 0 LightningResistance and takes 118 damage reduced from 118 damagePlayer attacks Floating Skull, it has 0 PoisonResistance and takes 0 damage reduced from 0 damagePlayer attacks Floating Skull, it has 0 ChaosResistance and takes 110.58 damage reduced from 110.58 damagePlayer attacks Floating Skull, it has 0 PhysicalResistance and takes 414.72 damage reduced from 414.72 damage</color>

#

thats the full form

#

i removed the newlines, same issue

quartz folio
#

And have you tried just logging that as a raw string, without reconstructing it?

glossy gust
#

how should I access a gameobject in ddol

merry stream
#

doesn't really matter anyway

quartz folio
#

There is no issue in my version of Unity, however cyan seems unsupported

spring creek
#

Basically pretend it isn't even in ddol
It's just a scene like any other

merry stream
quartz folio
#

6000.0.0b14

spring creek
#

Nice

merry stream
#

maybe thats it

#

im on 2022.3.14f1

#

im assuming thats a beta version ur using

#

should I update or do I risk breaking things, never updated before lol

quartz folio
#

I see no reason not to update to the latest f release for your version, as you can always roll back if you're using source control. As long as it's not changing major or minor version there shouldn't really be any meaningful changes that can break things

#

There's 9 releases that could have fixed the issue for you that are pretty much the same release as yours

merry stream
#

kk thanks

wary tinsel
#

hey fellas, still working on a 2d game and i need a pop up to appear with text when i get to scene i cant find any documentation about making these popups can someone help me out?

leaden ice
wary tinsel
#

like a UI popup

#

a modal

#

for my frontend goons

leaden ice
#

search for Unity UI modal

#

basically just activating a UI element

wary tinsel
#

need a box to pop up with a message explaining stuff

wary tinsel