#archived-code-general

1 messages · Page 48 of 1

hollow stone
#

From the image it does seem like it increments with 1 in the logs for each press?

nova python
#

it should do yeah

#

I have no idea why it's not incrementing the second time I press Jump but for the rest it will

#

1st Press: Counter = 1

#

2nd Press Counter = 1

#

3rd Press: Counter = 2

#

4th Press: Counter = 3

proper pier
#

@hollow stone Wait, I think it's possible that my spherecast is hitting my own player. If I put my player on it's own layer and exclude it from what you are allowed to grapple on to, would that prevent the spherecast from hitting my own player?

proper pier
nova python
#

spacebar

proper pier
#

did u try testing that on its own to see if it was the problem?

proper pier
#

I had a somewhat similar issue once

#

but not really

proper pier
#

@hollow stone Yay it worked! Thanks so much

nova python
proper pier
#

oh my b

#

that is so weird

#

the error is prrobably coming from somewhere else then

#

maybe you have something somewhere modifiying a public variable that it is not supposed to modfiy

#

that wouldnt really make sense tho since its all in 1 method

nova python
#

yeah

#

That's the only place it's been modified

#

wait no I'm wrong

#

when the player is grounded the index is set back to 0

#

During the jump the raycast is still hitting the ground and sets it back to 0 I bet

hybrid gale
#

hey guys i am struggling so hard setting up a database in unity does anyone have some suggestions? I tried mysql but the app for it was to much so i switched to firebase got around with the website easily but anytime i go to write code for auth functions it keeps saying my app is not found and ive re downloaded the sdk have the auth installed and my json for google

blazing smelt
#

How do people make thumbnails from images on a device? Because it seems like reading the entire image file is overkill when it's a large image and I only need a small sized graphic for the thumbnail.
I'm making a UI for selecting images from a camera roll

supple hinge
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

void basalt
#

Trying to RSA encrypt with a key generated from openSSL in php.


byte[] base64Bytes = Convert.FromBase64String("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4Q9oqSbWLu779TLQNkvd GRzzKhHtkZcJecz7N0E9RzwhqWztS5wnTzZMZGZRVzB/5hhZSh+U4xBnSbfs/y7q vC9kzzP2yZR5qwlWUjy3iPgtWtn7DbFZ8gdkVrTcubg9HC7TFtDcAE0DVg8jefFq 1eowQhkJgdEyyGORS1DO+fmhhciV/ahD/m3DiIWwNTvjllTHCqNSHEnR0SQO4hb5 HAEIf8kYNLtUCmboX7ZAKTY2+PyRMSRtN3cYEw91LUPu1Xcq0XPI3l1LfswdjaFB XKvFEgv/kzP7c2EYr3i5JvQKe4MFW5H9PxwEUQ7idwifGb0BICcKY+rdZTNchSq4 AwIDAQAB");

CSP.ImportRSAPublicKey(base64Bytes, out int bytesReadd);```

Gives me an "Operation is not supported on this platform." error.
#

I'm on .net standard 2.1 and the docs even state that it targets that framework

ionic socket
#

For whatever reason, when I call <mesh>.submeshCount I'm getting 1 instead of the 12 listed here?

empty wing
#

how can I have a raycast interact with the canvas?

ionic socket
empty wing
#

Im trying to make a setting in my game where I can drag and drop ui elements to allow my players to customize the hud in the way they want it to look, so I am using a mousepointtoray but it doesnt detect ui elements, is there a way to allow that?

ionic socket
#

typically you'd use camera.Main.ScreenPointToRay(Input.MousePosition) to draw a ray from your camera into the 3d space calculated by your mouse position.

#

also make sure to check into the drag/drop handers, IPointerDragHandler and it's sublings.

empty wing
#

okay thank you

unique cloak
#

I have a script which lets me drag objects with the script attached around in a grid-like fashion where they snap to coordinates of a particular "cell size" increment. heres the code https://hatebin.com/nalqhcnupz - unfortunately, this has an issue where every time I adjust the location of an object, it comes closer and closer to the camera, and theres no way to move it "backwards" to where it originally started. Does anyone have any suggestions for how I could go about fixing this? either a video showcasing an alternative system or some way I can manipulate the camera to avoid this little issue altogether? Any help appreciated, thanks

unreal temple
#

Okay, got a solution working!

using System.Runtime.CompilerServices;
using System;

namespace EffortStar {
  public class RuntimeCache<TKey, TValue>
    where TKey : class
    where TValue : class
  {
    ConditionalWeakTable<TKey, TValue> _table = new();
    Func<TKey, TValue> _calculate;

    public RuntimeCache(Func<TKey, TValue> calculate) {
      _calculate = calculate;
    }

    public TValue Get(TKey key) {
      if (!_table.TryGetValue(key, out var result)) {
        result = _calculate(key);
        _table.Add(key, result);
      }
      return result;
    }

    public void Clear() => _table.Clear();
  }
}
using UnityEngine;

namespace EffortStar {
  public static class AimInfoCache {
    public static readonly RuntimeCache<AttackActionConfig, AimInfo> Cache = new(GenerateAimInfo);

#pragma warning disable IDE0051
    [RuntimeInitializeOnLoadMethod]
    static void Initialize() => Cache?.Clear();
#pragma warning restore IDE0051

    static AimInfo GenerateAimInfo(AttackActionConfig config) =>
      config.CalculateAimInfo();
  }
}

Simple enough I guess, and prevents any unwanted changes persisting between runs.

dim furnace
#

Any idea why my player controller (in the bottom left) has its movement and rotation thingy in the top right?

gloomy swan
#

is NavMeshAgent.SetDestination() effect your performance? Like if I set a new destination every frame vs every second will it make any difference?

leaden ice
long glacier
#

hello, i must apologize if this is not the correct channel for this to post, but i need a ps3 webcam driver from github updated to support multiple cameras at the same time (very urgently)
if anyone knows how to implement this or by attempt, please write me
@ me

ionic socket
#

erm how do I set the material of a mesh at runtime? I'm calling mesh.materials[i] = myMaterial but it doesn't seem to change the default value

ionic socket
#

mesh.material = MyMaterial works for the first entry in the list; but does not work when I use the indexed reference.

mossy snow
#

copy to temp array, change the material in the temp array, assign it back to the mesh

kind grove
#

Are there any downsides to using the Enabled flag on scripts that don't update but I'd like to be able to turn on and off? They're reacting to other game events.

crude mortar
#

and "theres no way to move it "backwards" to where it originally started" isn't exactly accurate

#

but perhaps your code right now doesn't allow for it

fluid lily
#

I have an Object instance, Most things I assign to it are Monobehabiors/components, as I need the GameObject reference they are on so I cast them to Component, but I tried to put a GameObject as the Object and I am getting a cast exception. Is there something else I can cast Object to that would allow me to get the GameObject it is related to(aka itself if it is a GameObject)?

fluid lily
#

I mean I think GameObject would be the only thing not supported that could be assigned from editor so I can do a check for it.

ruby fulcrum
#

how do i prevent child objects from being scaled when i scale the parent

somber nacelle
#

either don't make it a child or scale it the opposite way

paper heart
#

i created separate thread for long math operation, but when it gets run, unity still freezes...
how can i do it so it doesnt freeze during the math calculation?

somber nacelle
swift falcon
#

for jumping Im using add force but its super inconsistent with the amount of force idk if its because i press the space bar multiple times during the jump or what

#

what is the best workaround or should i just set the velocity

somber nacelle
swift falcon
#

jumpforce = 1

somber nacelle
#

okay well for one, i'd recommend just calling the IsGrounded method once per Update rather than twice, there's literally no reason to call it more than once. but it is possible that you are being considered grounded for one or more frames after applying the force. What I normally do is I only check for ground when Y velocity is at or below a certain threshold, then reset the grounded state to false as soon as i jump so that it doesn't start checking for ground again until the object has started descending from its jump

#

also if you just want a single impulse of force you should consider using GetKeyDown instead of GetKey, this will also help prevent the object from applying the impulse force for multiple frames in a row

knotty sun
swift falcon
#

thanks it works much better now

elder temple
#

Is there a better way to get component of a triggered object, instead of using getcomponent in OnTriggerEnter()
??

somber nacelle
#

TryGetComponent in OnTriggerEnter

elder temple
#

But won't it run like every frame?

somber nacelle
#

no? OnTriggerEnter only happens when an object initially enters the trigger

elder temple
#

Ah...I thought it ran every frame

#

😅

#

Tnx

somber nacelle
#

even if that were the case, how else would you expect to get a component if all you are given is a reference to a Collider?

elder temple
#

Yeah..i thought there's a different way which I don't know of

fresh cosmos
somber nacelle
#

it is an event that you subscribe to. do you know how events work?

fresh cosmos
#

yeah, i added the event from basic c# class with [InitializeOnLoad] and added a test method to it in its constructor

#

it logged that it should have added the method to the event but it never logged that it triggered

somber nacelle
#

show the relevant code

fresh cosmos
#

hold on let me find it

somber nacelle
#

also are you certain you don't want to be using either RuntimeInitializeOnLoad (since the event you are subscribing to is only invoked during Play mode or in a build) or using the editor version of the event instead?

fresh cosmos
#

oh, that might be an good idea

paper heart
fresh cosmos
#

looks like i dont have the code on my laptop but i can rewrite it real quick its just a couple of lines

somber nacelle
fresh cosmos
#

i believe it was something similar to this

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using UnityEditor.SceneManagement;

[InitializeOnLoad]
public static class SceneChangeDetector
{
    private static Scene _previousScene;

    SceneChangeDetector()
    {
        _previousScene = EditorSceneManager.GetActiveScene();
        EditorSceneManager.activeSceneChanged += onSceneChanged;
        Debug.Log("Added to event");
    }

    static void onSceneChanged(Scene previousScene, Scene newScene)
    {
        Debug.Log("Trigger");
    }
}

somber nacelle
#

why not wait until you have access to the actual code to ask for help? then you can get help that won't require guessing at what the issue is

swift falcon
#

should i use a raycast or bullets with colliders for guns

fresh cosmos
#

i guess i can come back later when so i know for sure thumbsupani

lusty dragon
#

How do I change the layer in an object like this?

lusty dragon
#

Sorting Layer.

somber nacelle
#

i'm fairly sure that 3d renderers don't use a sorting layer

craggy cedar
#

In what order do Scene GUI Handles get drawn?

#

If I draw 2 handles in the same location

#

Which one comes on top

#

How do I control it?

#

I'm talking 2D, so I think I can change the Z position

vague slate
#

I remember Unity Editor has built in API to open explorer so you could choose a specific folder. Anyone remembers what is it's name?

maiden breach
#

Or one of the variants in the EditorUtility class? There are several depending on where/what youre looking for.

stark veldt
#

Hi.
I have a prefab that contains a certain amount of tagged objects.
Is there a way to count those objects on Scene launch prior to initializing any instances of that prefab?

leaden ice
#

and count

stark veldt
neon plank
#

Using NavMesh, is possible to add path restrictions to specific agents (not specific agent types, but specific instances of an agent)?
I would like for example: to disallow a specific agent from getting outside some rectangle(s).

main shuttle
timid meteor
#

Does anyone know how to set a position of a grid with a vector3int?

swift falcon
#

anyone know how to make a box collider hide all entities that enter it, but reveal those entities if the player also enters it? ChatGPT wrote an OK little script

timid meteor
hexed pecan
#

Show what you have attempted?

#

With a grid do you mean some sort of array or some grid component?

#

GridLayout?

thick plume
#

Does anyone have an idea why I'm able to instantiate the gameobject, but as soon as I try to add it to the list, I get NullReferenceException? I have no idea what could even try to figure it out

        ...
        static public List<GameObject> level;
        
        void PlaceItemOnScreen(Vector3 mousePosition)
        {
          ...
          GameObject gameObject = SelectedItem.selectedPrefab;
          gameObject.transform.position = prefabPosition;
          Instantiate(gameObject);
          level.Add(gameObject);
        }
#

the prefab gets instantiated as expected, it appears on my screen, but as soon as it tried to add to the list it errors

main shuttle
thick plume
#

sounds like an idea

#

ty

timid meteor
#

so this is just the part of the code that refers to the generation of terrain

#

what I am trying to do is

#

move the grid that generates the terrain via code

#

in the line

#

Vector3Int SpawnHere = new Vector3Int((int)SetGridPosition.transform.position.x, (int)SetGridPosition.transform.position.y, 0);

#

SetGridPosition is a gameobject that I assign a cube to that will make the grid active once the player has entered into the trigger box

#

the problem I am having is

hexed pecan
timid meteor
#

finding where to put SpawnHere

#

So knowing this how would you approach this?

hexed pecan
#

The GridLayout component is probably a good choice if you want to do conversions

#

Or anything grid based

timid meteor
timid meteor
hexed pecan
#

GridLayout can be used with code

hexed pecan
#

Calculate the offset with SetGridPosition.position - pivotPos where pivotPos can be your first grid position or whatever you want

timid meteor
#

hmmm ok I'll take a look into it thanks 😄

swift falcon
# hexed pecan Yes

here is what I attempted

using UnityEngine;

public class HideObjectsInCollider : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            foreach (Transform child in transform)
            {
                child.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");
            }
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            foreach (Transform child in transform)
            {
                child.gameObject.layer = LayerMask.NameToLayer("HiddenObjects");
            }
        }
    }
}
#

@hexed pecan what do you think?

hexed pecan
#

Do you mean to just hide them or disable them?

#

Also what object is this script on, is it the one that other objects enter?

#

Why would it hide its own children? Im confused

tepid river
#

i have this interactive (mini) map i built and now i wanna draw more information as text into the scene. whats the proper way to have text anchored to 3d objects?
i read you can make a canvas and glue that to the object, but i smell that this might be overkill?

vagrant blade
#

Just child it to the object

thorny spindle
#

You can also worldtoscreenpoint it

#

if you want to really put it on the canvas

tepid river
#

well i dont care about the canvas. i just want to anchor a bunch (20+) texts to different transforms

hexed pecan
tepid river
#

final

thorny spindle
#

oh, then just child it

#

But you'll probably want to make sure the text always faces the player

tepid river
#

so attach a canvas with a UI text to each object?

#

afaik UI texts need a canvas to work

vagrant blade
#

You can use the 3D textmeshpro object as well, no need for a canvas.

tepid river
#

cool thanks 👍

thorny spindle
#

Also I have a question

#

If in a game I have a bunch of items that I might want to add to later in some update

#

How would I take care of that list

#

like if I had a list of swords somewhere with sword1, sword2, sword3

#

But I added a sword4

#

How would I make sure that gets added to the list of swords so that I can iterate over the list to show in a menu later or smth

#

And how would I even add the sword?

hexed pecan
#

Where does that list live?

thorny spindle
#

Would it be an addressable asset that I push in an update or smth?

#

I haven't made any of this yet lol

#

This is just a problem I suddenly thought of, since I've never considered stuff like updates to a game after release

#

I guess.... would it make sense for the list to live in a scriptable object?

#

But then I would need access to the sword prefabs for instantiation at some point, so maybe it'd have to be a monobehaviour?

#

I guess I could have it be a scriptable object or smth, and then match the string of sword list and the prefab names and then something else in game could instantiate from resources

hexed pecan
hexed pecan
thorny spindle
#

Yeah, but I'm worried about how live updates would affect everything I guess

#

But I don't know how those work at all

#

Maybe that's what I should study next

tepid river
#

cool the TextMeshPro was exactly what i wanted.
cant believe how obsolete my "central canvas that imperatively positions UI images to screenpos of worldobjets" was

thorny spindle
#

Henlo to you too

thorny spindle
tepid river
#

i even resized the canvas images to simulate 3d space size differences catcrymic

thorny spindle
#

ouch

#

yeah, this way is better for what you want then lol

hard sparrow
#

How sus is a singleton that tracks state?

tepid river
#

uh depends. in my old project, the GameServer and GameClient were Singeltons

hard sparrow
#

I don't know anything about multiplayer or servers yet

#

(hoping to delay that since I know it will be very hard)

tepid river
#

best to just post your class, so we can smell it together

#

👃

hard sparrow
#

Well it's a status effect manager that can take a generic status type and matching enum to add a status from a list of prefabs to the specified unit

#

I figure I'll end up using FindObjectOfType on it most of the time anyway

#

How often do you guys use FindObjectOfType (or equivalent) ?

tepid river
#

if its a singleton, you dont need to find it tho.
just give it a public static MyClass instance

hard sparrow
tepid river
#

i try to avoid anything like Find. never use it.
but im not a gamedeveloper and not used to even have the ability to search for instances by class

swift falcon
#

Find isn't that bad : D

#

unless ur scene tree is HUGE

polar marten
#

if it isn't important that they are legible, you can put the text meshes in world space

hard sparrow
#

I'm using it a lot when implementing particular derived classes that implement and handle their own implementations - they find the classes they need and call the methods they want

polar marten
#

it is also sometimes, but rarely, expensive to render another camera. make sure your camera is configured correctly by putting all this stuff on a layer, and turning off unused features

hard sparrow
#

But then I think, if I'm using Find like this maybe I might as well make some of these managers singletons...

#

But THEN I think, well if this is my thought process I'll just end up making every manager a singleton, and that can't be right

tepid river
#

my former roommate did a unity project for his bachelor, and had almost no coding experience. so instead of properly managing a tree of references, he just had a ton of scripts and objects floating around somewhere and used search everytime.
THAT was a codesmell

#

a lot of managers are singletons by nature, doesnt mean you have to build them as such

hard sparrow
#

I think my architecture is pretty good. But it's not like I get any feedback on it so who knows

tepid river
#

also its kinda pointless to hand down a reference to your WorldManager or whatever into every single tiny object.
a public static getInstance() is much better

hard sparrow
#

K I'll just make it singleton. Might as well learn by doing

swift falcon
#

hence why DI is used for stuff like this but for some reason nobody in game dev which is making a client uses DI

tepid river
#

whats DI

rich girder
#

hello can somebody help me

swift falcon
#

dependency injection library

hard sparrow
#

DI?

swift falcon
#

It autowires the dependencies

hard sparrow
#

I heard from professional game devs that DI in gamedev is pretty pointless

swift falcon
#

.e.g.
Lets say you had

MyComponent(MyMenuManager manager)

#

It will autowire inside the object

rich girder
#

hello can somebody help me

swift falcon
#

so u dont need to deal with the object lifetime

swift falcon
#

THIS IS A HELP CHANNEL

#

DI is pretty nice for decoupling logic

hard sparrow
swift falcon
#

its not used at all unfortunately

#

in every part of software development we generally use DI

#

to wire up constructor dependencies

#

You can use stuff like myDiContainer.AddSingleton<MenuManager>()

#

then it'll automatically resolve it

#

when myDiCotainer.Dispose is called it disposes all the services

tepid river
#

not a fan of dependency injection mostly. it hides a lot of things and makes understanding stuff more difficult.
still has its usages oc

swift falcon
#

So u dont have to handle the lifetime

#

the beauty of the DI is u dont have to handle construction or lifetime of the object

hard sparrow
#

I would need to see an example to understand

swift falcon
#

tbf nothing that the client uses

#

for some reason people dont use DI in game clients

hard sparrow
#

When I was learning to code (explicitly for purposes of game dev) I spent like two weeks trying to understand DI, not really succeeding, and then never using it anyway after hearing some gamedev pros trash talk it in gamedev context

swift falcon
#

for game servers its a differen story 🙂

#

In enterprise DI is used for nearly every large application

#

except in the gaming industry for game clients.

#

better examples

hard sparrow
#

What are the kinds of situations where you start thinking about using DI?

swift falcon
#

When you have a huge amount of dependencies in your services which can change, or when you have dependencies and you dont want to manage their lifetimes and creation yourself

mental lava
#

if im using unity on Linux, is it recommended to use vs code? if not, what other alternatives do you guys suggest

hard sparrow
#

"dependencies which can change" as in a class depends on a certain class at one time, and a different class at a later time?

tepid river
#

VSC works well on linux (for my work, dont know about unity)

swift falcon
#

.e.g.

MyConstructor(MyDependency dep) {

}

MyDependency(AnotherDependency1 dep1, AnotherDependency2 dep2) {

}

Now normally without DI i will need to do:
new MyConstructor(new MyDependency(new AnotherDep1(), new AnotherDep2()))

With DI you can just do:

serverProvider.GetComponent<MyConstructor>()

#

It will new up the objects automatically

#

and handle them

#

ofc u need to register them .e.g.
serviceProvider.AddSingleton<AnotherDependency1>();
serviceProvider.AddSingleton<AnotherDependency2>();
serviceProvider.AddSingleton<MyConstructor>();

hard sparrow
swift falcon
#

you can see the benefits right here.

swift falcon
#

Ability to easily change out deps is a nice one

#

now whenever you reference IFileSystem in a constructor it will automatically resolve the correct one registered in the DI

rich girder
#

hello can somebody help me

tepid river
#

dude just ask your question

rich girder
#

how do i fix this problem

tepid river
#

looks like your code editor is set to something wierd (at least thats suggested in the error)

#

check edit>preferences> external tools

swift falcon
rich girder
tall lagoon
#

Hey guys so im making an fps and im making a big room for a level but for some reasonwhen the walls are are the walls do this bc of the camera.how can i fix?

hexed pecan
brittle sparrow
#

yeah sorry

hexed pecan
brittle sparrow
#

it used to

#

that's the weird part

#

maybe I need to restart unity

tepid river
swift falcon
# hexed pecan Do you mean to just hide them or disable them?

either is fine. The script I posted would be attached to the collider. It's to hide enemies, other players, and objects on 2nd and nth floors of buildings while the player is on the lower floors in a top down game. The approach was to have a tag or layer for hidden objects and add and remove objects from that tag or layer as they enter or exit the trigger. Maybe there is a better way?

hexed pecan
#

Well the script is hiding/showing its own children instead of the one its colliding with, so I'm not even sure if it works correctly

swift falcon
#

that's probably why it doesn't work or do anything

#

because it can't parent itself to objects dynamically... How can I make it so that it works on collision / trigger enter and exit

tepid river
vagrant blade
#

You install visual studio either manually from the website or through Unity Hub.

whole night
#

I have a bunch of objects that i instantiate and i have a follow script on them and they follow me, but how do i set their rotation to face me?

leaden ice
gray zephyr
whole night
leaden ice
neon plank
hexed pecan
hexed pecan
hexed pecan
tepid river
swift falcon
# hexed pecan Was this the script written by ChatGPT?

yes it was lol 🤣 I wrote my own script for hiding/toggling roofs and floors when the player collides but this was a starting point for hiding players and monsters (and other objects) on other floors because it seemed like a really complex task

swift falcon
hexed pecan
swift falcon
whole night
#

if i want to do onCollisionEnter do any of the two GO need to have rigidbody ?

rich girder
#

what is wrong in this comand help me

#

it puts syntaxs eror ;;

whole night
knotty sun
knotty sun
zinc parrot
#

Are there any examples I can follow yet of inline raytracing in unity? from what ive seen the documentation on it is very very sparse

night relic
#

hello, does anyone know how can I get informed when recenter event occurs (right Oculus menu button long press) with XR Plugin Management?

#

target is to implement recenter in my app on right Oculus menu button long press...

vagrant marsh
#

does anyone know good examples of enemy ais in sidescroller games?

covert nest
#

hey everyone, is there any way to get a sprite into a tilemap with code? i couldnt find any helpful information about it on the internet pls help me out

valid relic
#

Hey, I need to sort small lists (usually 1-20 elements, rarely above 30) extremely efficiently. The keys are positive floats. They tend to be near-sorted a lot of the time so the default quicksort used by List.Sort() may be the bottleneck, and I'm looking for a better algorithm for this scenario.

Here is an example of a typical list:

[14.43493, 65.56322, 172.989, 213.8974, 257.5395, 324.424, 346.906, 357.6949, 368.1883, 0.2753617, 0.419436]

As you can see the list is almost sorted, except for the last two elements which are at the wrong end. It is quite common for the list to be made up of some number of ordered subsequences. As such, what is the most efficient sorting algorithm for this? I am thinking of using Insertion Sort but it does not take advantage of the subsequences being sorted. I would prefer one which splits up the list as such and re-orders the subsequences based on their first and last element, and handles overlaps appropriately:

[14.43493, 65.56322, 172.989, 213.8974, 257.5395, 324.424, 346.906, 357.6949, 368.1883], [0.2753617, 0.419436]

Does something like this exist? Would handling overlaps be too big an overhead?

cunning sleet
#

Question! I'm positioning a bunch of walls right next to each other with this line of code:

wall.transform.position = previousWall.transform.position + -1 * previousWall.transform.up;

The issue is that they are getting spawned/positioned directly next to the previous spawned-in wall while the wall is moving. This leads to some inconsistencies on where the walls actually get spaced. How can I ensure that they are always directly next to each other (no space between)?

#

Note: If the walls are not moving, they spawn in correctly. I think its an issue with the previous wall moving a pixel or two during the calculation of the next one.

knotty sun
cunning sleet
knotty sun
hexed pecan
#

You could try rigidbody.position instead of transform.position

#

Im assuming youre updating previousWall to be the newest wall after creating it?

cunning sleet
cunning sleet
cunning sleet
knotty sun
# cunning sleet What do you mean by caching the position here?

it would seem that there is a mismatch between position and actual position. As you are using physics then this would indicate a mismatch between Update and FixedUpdate positions, so you have a choice, move your code to FixedUpdate or cache the FixedUpdate position and use it in Update

swift falcon
#

What is going on with my compute shader, why are the alpha maps being tiled like that?
I have 8 terrain layers and the compute shader sets the alphamaps for the terrain using a texture2d to find the closest color from the terrain layer diffuse texture, but its not working the way its intended to work.

The 1st image its how im getting the result from the GPU, and the 2nd image is how im getting the results from loops in C#.

Code:
https://gdl.space/hiyiyowecu.cpp

cunning sleet
untold siren
#

hi guys I'm stuck on a current issue with coding a shotgun that uses raycasting to give it an accurate and randomized spread; it can randomize it's point however I'm using a trail renderer to imitate that it's actually shooting a projectile. I'm trying to figure out how to still draw a trail even if the raycast is unsuccessful; by trying to use the direction of the ray but it's not working - if anyone has a realistic method of going about implementing this, it'd be heavily appreciated. the current code is:

        private void ShotgunFire()
        {
            for (var i = 0; i < shotgunPelletCount; i++)
            {
                var accuracy = Random.insideUnitCircle * shotgunSpreadSize;
                var dir = new Vector3(accuracy.x, accuracy.y, 1f);
                var sprayDir = transform.TransformVector(dir);
                Debug.ClearDeveloperConsole();
                Debug.Log(accuracy);
                var ray = _playerCamera.ScreenPointToRay(Mouse.current.position.ReadValue() + accuracy);
                var targetPoint =  Physics.Raycast(ray, out var hit) ? hit.point : -sprayDir * 30f;
                TrailRenderer trail = Instantiate(bulletTrail, shotgunSpawnPos.transform.position, Quaternion.identity);
                StartCoroutine(SpawnTrailAlternative(trail, targetPoint));
                switch (hit.transform.tag)
                {
                    case "Enemy":
                        var collidedEnemy = hit.transform.gameObject;
                        collidedEnemy.GetComponent<EnemyController>().TakeDamage(shotgunDamage);
                        break;
                    case null:
                        break;
                }
            }
            CurrentAmmo--;
            if (CurrentAmmo > 0) return;
            _playerInventory.ExpireWeapon(_playerInventory.CurrentCard);
      }
#

I've also tried it with this

                var targetPoint =  Physics.Raycast(ray, out var hit) ? hit.point : ray.direction * 20f;
#

however it doesn't shoot straight ahead and instead either to the side or behind the player

elfin vessel
#

How can I change the editor camera's position from a script?

elfin vessel
leaden ice
#

I assume currentDrawing is only set during a scene view repaint or whatever

empty wing
#

I am trying to change the pivot point of a hud element to the location of a mouse input, but im struggling on converting the pivot point to world space. How can this be done?

leaden ice
empty wing
#

oh damnnnnn

elfin vessel
empty wing
#

that was probably the most useful thing someone has ever said to me ever, that would have changed everything sixteen centuries ago

#

thank you

leaden ice
grim copper
#
UnityEngine.AI.NavMeshAgent:SetDestination (UnityEngine.Vector3)```

how do i fix this
#

i've got a baked navmesh on my floor

#

and a navmeshagent

elder spoke
#

hello 🙂 My objects have no shadows as you can see in the image, any tips? thanks!

elder spoke
#

okk, thanks

deep willow
#

When should I be using a Singleton Pattern?

#

I have a player script and there will only ever be one player

#

wondering if its worth making it into a singleton

wraith coral
#

is there a quick way to get a scene’s build index using the scene’s name?

hexed pecan
#

Why do you need this though?

wraith coral
wraith coral
void basalt
#

            Buffer.BlockCopy(webRequestBuffer, 0, webRequestBytes, 0, 1024);
            Decoder myDecoder = Encoding.UTF8.GetDecoder();

            // Full string no problem
            Debug.Log(new string(webRequestBuffer));

            myDecoder.Convert(webRequestBytes, 0, 1024, webRequestBuffer, 0, 1024, true, out int one, out int two, out bool three);
            
            // Only first letter, despite char buffer being full
            Debug.Log(new string(webRequestBuffer, 0, 1024));```

After the decoder convert, the char array is having trouble getting processed back into a string
#

When I create a new string with that char buffer after the convert, it only copies over the first character to the string, no matter what I do

#

before the conversion, the entire char buffer goes into a string just fine

#

The char buffer is also full of characters after the conversion. I can see if I loop through them

elder jay
#

Help

plucky karma
# elder jay Help

Saying "Help" with absolutely no content to what problem you're having is difficult to answer.

elder jay
#

I have a [SerializeField] Camera worldCam; but when I try to add the camera it doesnt let me

void basalt
#

That's a beginner question pal

elder jay
#

my bad

plucky karma
elder jay
#

its a camera though

#

it does have a camera component

void basalt
#

drag the component in, rather than the gameobject. If that doesn't work, just grab it through C#

#

Camera myCamera = GameObject.Find("someObjectWithCamera").GetComponent<Camera>();

elder jay
#

ill try that

#

because dragging it just does nothing

void basalt
#

Then you're doing something wrong

elder jay
#

thats what Idk what Im doing wrong

void basalt
#

Screenshot your object with the camera

#

the hierarchy view.

elder jay
#

Im trying to drag the main camera

void basalt
#

Which object is your camera component on

#

oh nevermind

#

Just drag the main camera on to your variable

#

If that doesn't work then you need to screenshot the inspector view of the variable

elder jay
#

when I drag the camera in, it lets me but then it doesnt add the camera

void basalt
#

I'm not much help. I don't drag stuff in, I usually just initialize through C#

#

Sorry

#

I think to drag stuff in, it has to be in the same hierarchy

#

Like you can't drag a camera from your scene inspector hiearchy, into your asset in your asset folder

elder jay
#

hmm

void basalt
#

But that's weird because your game controller is in the same hierarchy view

elder jay
#

yeh

void basalt
#

Make a new camera in your scene inspector view

#

right click -> new camera

#

try with that

elder jay
#

I tried that

#

it did the same thing

void basalt
#

restart unity?

elder jay
#

tried that

void basalt
#

Just out of curiosity, change [SerializeField] Camera worldCam; to public Camera worldCam;

elder jay
#

k

#

same thing

void basalt
#

no clue then

elder jay
#

dang

void basalt
#

You will have much better luck in the beginner section

elder jay
#

k

cosmic rain
elder jay
plucky karma
#

@elder jay Click on this and see what pop up on the list -

elder jay
#

still didnt work that way

chrome berry
#

It's probably not the case here, but an OnValidate that immediately nulls the reference could do something like that.

plucky karma
#

Something seems very wrong with this....

chrome berry
#

Though from the video, it looks like it's not letting you drop it in. It's got the crossed circle when you hover over the reference field

cosmic rain
#

In this case they might have a class called Camera in the project.

elder jay
# cosmic rain Share the game controller script
using System.Collections.Generic;
using UnityEngine;

public enum GameState
{
    FreeRoam, Battle
}

public class GameController : MonoBehaviour
{


    [SerializeField] PlayerController playerController;
    [SerializeField] BattleSystem battleSystem;

       [SerializeField] Camera worldCamera;
    
    
    
    //public Camera worldCamera;

    GameState state;
    // Update is called once per frame

    private void Start()
    {
        playerController.OnEncountered += StartBattle;
        battleSystem.OnBattleOver += EndBattle;

       

    }

    void StartBattle()
    {
 
        state = GameState.Battle;
        battleSystem.gameObject.SetActive(true);

        //worldCam.gameObject.SetActive(false);

        var playerParty = playerController.GetComponent<PokemonParty>();
         var wildPokemon = FindObjectOfType<MapArea>().GetComponent<MapArea>().GetRandomWildPokemon();

         battleSystem.StartBattle(playerParty, wildPokemon);
    }


    void EndBattle(bool won)
    {
        state = GameState.FreeRoam;
        battleSystem.gameObject.SetActive(false);
        //worldCam.gameObject.SetActive(true);
    }




    private void Update()
    {
        if (state == GameState.FreeRoam)
        {
            playerController.HandleUpdate();

        } else if (state == GameState.Battle)
        {
            battleSystem.HandleUpdate();
        }
    }
}
chrome berry
#

So it thinks the object you're dragging in DOESN'T match the reference field's type

plucky karma
#

Try this, see for sanity checks?

[SerializeField]
private Camera _cam;
public Camera Cam 
{
  get => _cam;
  set {
    _cam = value;  // add a breakpoint here, see the stack trace?
  }
}

Change all of your camera reference to use "Cam" instead.

elder jay
#

k

cosmic rain
#

It kinda looks like their pointer is offseted too..?

#

Perhaps the field doesn't get the drop down event.

chrome berry
#

Here's another (unlikely) possibility: Do you have a script called Camera that you made yourself?

plucky karma
plucky karma
#

Why

#

Don't ever do this...

elder jay
#

I was testing stuff

#

let me Nuke it

plucky karma
#

Refrain naming your class with an already existing class name, how is it that you haven't receive any compiler errors?

chrome berry
#

If you ever need to make your own scripts that have the same name as UnityEngine stuff, put it into a namespace to avoid ambiguity

plucky karma
#

Something awfully suspicious here, if that was the case.

elder jay
#

I completely forgot about that Camera script

plucky karma
#

Ah yes... the namespace...

elder jay
#

it works

#

yay

chrome berry
#

Ah ha, unlikely possibility FTW

elder jay
#

thx so much

#

Thats the last thing I needed to finish my project

restive dirge
#

I have a game planing going on in which player squats with the mobile by keeping the mobile in landscape left format, is it possible to identify whether player is squatting accurately with his mobile, currently we have an idea of checking mobiles accelerometer values but its not accurate ,

void basalt
restive dirge
void basalt
#

Oh, for some reason I read the word "multiplayer" in your text

whole night
#

can you use shader graph if you dont use URP ?

brisk marsh
restive dirge
brisk marsh
whole night
#

can you use shader graph with normal renderer pipeline(I am not using URP or HDRP) ?

chrome berry
#

AFAIK, no, it's URP and HDRP only

unreal temple
#

So if I have 5 vertices, then 10 vertices, then 4 vertices, I will need to create a new array each time.

#

How can I do this without throwing arrays in the garbage each time?

polar marten
polar marten
#

i think this is what this arraypool class is for

plucky karma
#

Could use ShaderForge 😄 @whole night

leaden ice
unreal temple
#

Guess that's an option.

#

Pretty annoying they don't let you pass a length in with the arrays.

#

Retrieves a buffer that is at least the requested length.

#

wont' work, but I could make my own

foggy tree
#

Looking for a person to create a mobile game. write in private messages

tawny elkBOT
unreal temple
#

Why do all Mesh.SetTriangles overrides take a submesh? If I use 0 for the submesh will that apply to the single mesh?

#

For SetVertices we have:

public void SetVertices(Vector3[] inVertices, int start, int length, Rendering.MeshUpdateFlags flags = MeshUpdateFlags.Default);
quartz folio
#

Because Unity's meshes are made of of a single vertex array and any number of submeshes (indices into that data)

#

If you only have one submesh in the first place, then yes, 0 is the single mesh

lean wagon
#

Hi, i want to make a plane with the shape of my Field of View

using UnityEngine;

public class ViewportQuad : MonoBehaviour
{
    public Camera camera;
    private float distanceToCamera;

    private MeshRenderer meshRenderer;

    private void Awake()
    {
        meshRenderer = GetComponent<MeshRenderer>();
        distanceToCamera = 0.5f / Mathf.Tan(0.5f * camera.fieldOfView * Mathf.Deg2Rad);
        UpdateQuadSize();
    }

    private void Update()
    {
        UpdateQuadSize();
    }

    private void UpdateQuadSize()
    {
        if (camera == null || meshRenderer == null) return;

        float aspectRatio = camera.aspect;
        float screenWidth = Screen.width;
        float screenHeight = Screen.height;

        float quadHeight = 2f * distanceToCamera * Mathf.Tan(0.5f * camera.fieldOfView * Mathf.Deg2Rad);
        float quadWidth = quadHeight * aspectRatio;

        meshRenderer.transform.localScale = new Vector3(quadWidth / screenWidth, quadHeight / screenHeight, 1f);
    }
}

can someone tell me what i have to change to achieve that? i dont see my mistake

#

the scene looks like this

quartz folio
#

I don't understand why you're dividing by screen width and height, or why you're calculating the distance if your quad was 1 high?

#

Where do you actually want this quad in space?

#

If it's where it is already, then surely you want to be using the distance it is to the camera at some point? And not just calculating something else entirely

vague slate
#

Is there a way to get current scene load handle? Particulary for first scene load

lean wagon
#

my actual goal is to create a plane to resterize the scene at that region and then compare the values with the values in the Field of View.

i tought i create a plane and position it at the field of view and with the script it should scale to the field of view

quartz folio
unreal temple
#

You'll only have multiple scenes if you load additive

vague slate
#

🤔

#

is that supported in runtime or editor only?

unreal temple
#

Runtime!

#

All the SceneManager stuff is runtime. There's an editor version too if you need it

#

But that's quite a different use case.

vague slate
#

🤔

unreal temple
#

?

vague slate
#

that's very interesting

unreal temple
#

isn't it what you wanted?

#

oh wait... "scene load handle"

#

I don't know what that is

#

This is to get a handle to the scene itself

vague slate
#

when you load scene you get operation handle

#

which provides you data about current loading operation

unreal temple
#

Ah, well there cannot be a load handle to the current scene because the current scene would already be loaded

unreal temple
#

I believe the first scene loads before any code runs, but what you can do is have a very lean scene that is your loading scene

#

And put a single script in that that loads your scene in the background

#

I have our company logo/splash in a scene like this

vague slate
#

you can run code at any point of time

#

even before all dlls are loaded

unreal temple
#

Hm. Okay, well I'm not sure how to do that

vague slate
#

through attributes on static methods

unreal temple
#

Like RuntimeInitializeOnLoad?

vague slate
#

yeah

unreal temple
#

Sure.

#

I am assuming here that you're trying to do a loading bar or similar

vague slate
#

yeah

unreal temple
#

Well...

#

You can't do that until you have a rendered frame

#

And you can't have that before the first scene is loaded

vague slate
#

damn, additive scene load is a game changer lol

#

Is that 2021 feature?

unreal temple
#

So I'm not really sure what RuntimeInitializeOnLoad has to do with it

vague slate
#

I'm pretty sure it wasn't here before

unreal temple
#

It was available in 2017

#

So it's at least 6 years old

#

Looks like it was introduced in 5.3

#

So 2015

vague slate
#

😮

unreal temple
#

I do basically all my scene management via additive scenes

vague slate
#

yeah, this should be indeed very interesting

#

but I'm so sceptical about it, so I literally making a build rn to check it works runtime xD

unreal temple
#

lol I have shipped games that use it

#

It works

vague slate
#

Can't believe it until I see it with my own eyes 😅

vague slate
#

@unreal temple sir, what about runtime scene saving? Are you familiar with that sort of stuff?

unreal temple
vague slate
west lotus
#

The way we have done a runtime editor is treat like a save game. Serialize the changes to the scene in our own data format and then recreate it at runtime

vague slate
#

sure, that's the thing, but I'm curious for scene format

#

cause if that's a thing, I don't have to write my own format

west lotus
#

Im pretty sure that the yaml scenes are stored in gets crunched into some unity black box format when build

grand rain
#

how to i get the rotation of transform as if it used lookat? i want to smooth it))

worthy cape
#
    public void DisplayMessage(string text, Sender sender)
    {
        Image messageBox = Instantiate(_messageBox, _scrollRect.content);
        TextMeshProUGUI messageText = Instantiate(_messageText, _scrollRect.content);

        messageText.gameObject.SetActive(true);
        messageBox.gameObject.SetActive(true);

        messageText.text = text;
        messageText.ForceMeshUpdate();
        Bounds bounds = messageText.bounds;
        messageBox.rectTransform.sizeDelta = bounds.size;
    }

messageText.bounds.size is very inaccurate and also very big, i am not sure what's causing this, does anyone know why?

tepid river
#

i have a worldscene and i have built an interactive map.
when i press M i want to switch between both views.
Whats a proper way to handle that?
have world and map in two gameobjects, only one enabled at a time?
disable worldcamera, enable map camera?

drowsy harbor
#

Hello all, I would like to ask you.

I am working on my asset (which possibly could be published to asset store). How I can ensure in my code - that even the end-user change the folder based on his requirements (for example to Assets/3rdParty" folder) How I can check / setup my code that it always will have an access to correct "asset folder" ?

tired drift
#

Hey hey guys, I've a doubt about which would be the best approach for a zoomable and scrollable 2D grid map.
Explaining a bit of the idea, it would be having an image that would be the background of the map, and the game would develop there. I would have a grid to create events on certain points of the grid, create NPC movements etc.

I have in a certain way a structure for the gridcell already defined (I can provide it, but i don't think it's necessary for what i'm looking for) and some base code.

Here are the following problems i've found so far (And idk how to handle):

If i use an GameObject to hold the image and then use the camera to zoom in and out, it may present some errors when it comes to the Aspect ratios and maybe it could potentially zoom out a lot? (The zoom can be fixed by having an underlay with the same background color as the map.

If i use an image in a canvas, the image can be zoomed (scaled) but the grid won't do the same thing. (Can this be the best way to approach it but handle the zoom + X/Y position of the click?)

Has anyone ever done a grid system in a 2D world that can be zoomed in or zoomed out that could kinda point me in the right direction?

unreal temple
vague slate
#

well yeah, it seems like that's the only choice so far

#

quite weird they implemented runtime scene creation

#

but no runtime serialization of it

rain meadow
#

I wonder if any of you guys would be able to help me set up an IK rig for a character from Mixamo with the animation package? I'm pulling my hair out a bit over this!

warped dust
#

Guys I have wierd results with camera.WorldToScreenPoint.
worldPos = new Vector3(7.58f, 0f, 4f);
camera.WorldToScreenPoint(worldPos) returns (4699201.00, -2872043.00, 0.00)
What am I doing wrong? My camera setup:

#

Why are the values so big

frosty pawn
#

Hi guys! What is the best way today of culling UI elements. I want to disable UI element gameobject when it outside of scroll view.

lost delta
#

I am looking for the quickest way to optimize drawing sprites without the overhead of thousands of game objects.
Simplifying the images to tiles and drawing tiles worked fairly good, but I don't get to place them in-between the tiles.
I think going straight to applying pixels to a texture may be even better.

So I tried SetPixels(), on to a separate texture, and only apply it to the screen when it gets through all of the characters. (lets call them goblins) Eventually this will be multi-threaded, but for now I am just limiting the amount of time it has, to keep a reasonable frame rate. It picks up where it left off the previous frame)

Anyway, 100,000 of my little 8x8 pixel image takes about 12 frames to be drawn when formatted as a R8, and also unchanged as RGBA 32 bit. I would expect a performance increase with the shorter bit format.

Does anyone have advice for the fastest method to do this? I would love to be able to push this up to 1,000,000 characters processed, even if I have to slash down the image quality.

Thanks

lost delta
#

nope

lost delta
frosty pawn
#

@lost delta I think when case is 1kk of something rendered then you should look at GPU instancing

lost delta
#

I am sticking to 2d if that makes a difference

frosty pawn
#

@lost delta no difference in result, but I would expect difference in performance. Instancing happens all on GPU side, so CPU not loaded so much. In your case you doing tones of work (1kk coping something to same texture) on CPU and then just 1 simple drawcall on GPU

lost delta
#

hmm... are Tilemaps GPU instanced?

frosty pawn
#

@lost delta guess it's not, because you can use regular material with GPU instanced checkbox disabled. I think tilemaps do some performance tricks though

lost delta
#

lol very small spaced tiles. about one pixel across😅

frosty pawn
#

I think that the problem is always not in how many pixels you have but in how many actions your CPU does to render it

main shuttle
#

This is one of the best use cases for DOTS, so why don't you use it? 1.000.000 should be easily doable in DOTS.
There are a bunch of examples, some in older versions of people that have animated sprites in DOTS already.

lost delta
#

I mostly haven't used it because I am unfamiliar with it. But my 8 byte array ends up being 8 megabytes when I have 1,000,000 instances, and it is hard for me to imagine using a game object would be more efficient. I suppose the efficiency here is drawing them, not holding their information in ram.

frosty pawn
#

It's not about holding something. It is about all times you rewriting data to texture. If it happens ones or really rarely then ok, that is your case. But if your 1kk goblins will run and jump across the screen, then you will ended up with writing to texture 1kk times.

main shuttle
# lost delta I mostly haven't used it because I am unfamiliar with it. But my 8 byte array e...

https://github.com/fabriziospadaro/SpriteSheetRenderer
This was the one I used ~a year ago, the problem that this one only did 1 million, was because the sprites overlapped, which caused z-fighting, which dropped the FPS significantly. When spaced out I got way more. With the new versions of entities, you get way better performance then 0.17, so I wonder how many millions of sprites you could get if you updated this. Anyhow, I think this is a way better approach, at least for the sprite rendering part. You can also go hybrid if you want.

frosty pawn
lost delta
#

Thank you both so much! I will look into this

west lotus
main shuttle
tall fog
#

It is possible to save the child (Camera) before destroying its parent?

frosty pawn
tall fog
#

Description

Unparents all children.

Useful if you want to destroy the root of a hierarchy without destroying the children.

See Also: Transform.parent to detach/change the parent of a single transform.

#

I tried DetachChildren too, but it didn't work

primal wind
#

Try setting the parent to null?

tall fog
#

That's what I'm trying

#

I guess Camera.main.transform it's already null

brittle haven
#
{
Instantiate(PlayerListItemPrefab, playerListContent).GetComponent<PlayerListItem>().SetUp(player);
}``` gives an error like: ```The type or namespace name 'Player' could not be found (are you missing a using directive or an assembly reference?)``` why isn't it working?
mellow sigil
#

Do you have a class called Player?

brittle haven
#

this should be in the photon

#

i use photon

sacred frost
#

import the namespace?

brittle haven
#

yes

stable rivet
brittle haven
sacred frost
#

im not sure really lol

#

try to import the package again or whatever

brittle haven
#

ok i will try

polar marten
#

what are you trying to do?

#

and do you have a screenshot of your game?

stable rivet
polar marten
#

lol

polar marten
#

like what's the game?

#

destructible terrain?

lost delta
#

like.. tilt your phone and thousands of little guys roll over to that side of the map

stable rivet
# polar marten lol

check dms - expecting to see this littered around the code channels soon 😄

slim spruce
#

Hi! I'm currently experiencing a bug where the rope on my character's fishing rod seems to "lag behind" a frame or so. The rope is made out of a LineRenderer, as well as some kind of gravity simulation for the rope as well as the hook.
I've tried putting the DrawFunction in LateUpdate, FixedUpdate, Update, and OnPreRender. Regardless of the method used this resulted in the same bug, with OnPreRender being the exception where the rope didn't render at all. The rope is also on an overlay camera that only renders weapons. Unchecking "Use world space" temporarily fixes one of the rope segments, but breaks the other.

This code wasn't written by me, so I'm not exactly sure where to start looking to debug something like this. I'd appreciate any help available with this. Thanks!

polar marten
polar marten
slim spruce
polar marten
# slim spruce I understand that, trying to give as much information as possible so I at least ...

right now what is happening is

  1. start of frame
  2. the position of the line renderer is calculated with respect to the position of the fishing rod. at this point in time, the fishing rod's position is still the same as it was in the previous frame.
  3. the player's input is read and the movement is applied to the camera
  4. the fishing rod is repositioned with respect to the camera. at this point, the line renderer appears to be in the wrong place.
  5. render the frame

or

  1. start of frame
  2. the player's input is read and the movement is applied to the camera
  3. the position of the line renderer is calculated with respect to the position of the fishing rod. at this point in time, the fishing rod's position is still the same as it was in the previous frame.
  4. the fishing rod is repositioned with respect to the camera. at this point, the line renderer appears to be in the wrong place.
  5. render the frame
lost delta
polar marten
slim spruce
spark shore
#

Is it possible to track Flick speed/inertia using a mac trackpad in Unity?

polar marten
spark shore
polar marten
#

clearly the order of the LateUpdates are not in the order you want*

lost delta
slim spruce
polar marten
#

well the snippet i described is what's happening

#

i can't see your code, so i don't know which callbacks you are putting this stuff into

#

it sort of doesn't matter

#

the positioning of the rope is strongly coupled to the fishing rod's position

slim spruce
polar marten
#

i don't think it's strange, exactly what i am describing is what's happening

#

this can be easily resolved by moving the code that positions the fishing line points to be after the fishing rod is positioned with respect to the camera

#

LineRenderer itself may use LateUpdate to update the mesh with respect to the points. so if you are doing this all in a LateUpdate, you may have to call a method on the line renderer to update the mesh manually after you have changed its positions

slim spruce
polar marten
#

none of that matters

#

the rope is simply strongly coupled to the position of the fishing rod. you have to do that work in the same place

#

it cannot be decoupled like it is now

#

this is using fixed update to move around the points. the camera will be "later" than a fixed update

#

the reason the gap is big is because the camera is positioned on update, where the input is read

#

but fixed update is run before update, so the input is from the previous frame

#

i.e., the apparent camera position read by the fishing rope is the previous frame's camera position, and hence the previous frame's fishing pole position

#

look at my snippet. that is what's happening

slim spruce
#

alright, sorry for asking irrelevant questions. I greatly appreciate the help, really. thanks for explaining this so thoroughly. I'll take a crack at it and come back if I have any more questions.

polar marten
#

am i making sense?

#

you have to find the code where the camera is positioned with respect to player input.

#

After that occurs, you have to calculate at least the first few positions of the fishing line with respect to the fishing pole. it sounds like the pole is a child of the camera transform, so its position will have been updated at that point

#

then you have to apply the positions

#

then your bug is solved

slim spruce
polar marten
#

lol

#

i'm sure [you]'ll figure it out!
i'm supposed to say this part when someone is really confused, not the confused person

slim spruce
#

pfft well fair enough. the step by step breakdown helped a ton in understanding it all though, so thanks again!!

grim copper
#

I've got a code that rotates the enemy's gun towards the player so that the enemy can shoot the player. But, the attackPoint (which is at the barrel of the gun) doesn't shoot straight but sideways. and when the gun rotates towards the player the barrel doesnt face the player, instead the side of the gun faces the player.

        Transform attackPoint = enemyGun.transform.Find("attackPoint");
        if (Physics.Raycast(attackPoint.position, direction, out hit, Mathf.Infinity))
        {
            // Rotate the gun towards the hit point
            Quaternion targetRotation = Quaternion.LookRotation(hit.point - attackPoint.position);
            enemyGun.transform.rotation = Quaternion.RotateTowards(enemyGun.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }

        if (!alreadyAttacked)
        {
            // Attack code here
            Rigidbody rb = Instantiate(projectile, attackPoint.position, Quaternion.identity).GetComponent<Rigidbody>();
            rb.transform.forward = attackPoint.forward;
            rb.AddForce(enemyGun.transform.forward * shootForce, ForceMode.Impulse);
            rb.AddForce(transform.up * upwardForce, ForceMode.Impulse);
            // End of attack code```
#

idk how to fix this

leaden ice
grim copper
leaden ice
#

with tool handle rotation set to local, if you select the gun object, the blue arrow should align with the barrel of the gun

grim copper
#

how do i make it match then?

I just got the blend file and dragged it into my models

leaden ice
#

if it doesn't, you need to fix the model export from blender

grim copper
#

oh yeah it doesn't

#

it matches the side

leaden ice
#

Now you know your issue

whole night
#

I have a audio clip whose volume i want to reduce, how do i do that?

#

doing audioSource.volume = 0.3 does not reduce the volume

soft shard
static matrix
#

how can I make a TMPro TextMeshPro appear above its parent, which uses a normal sprite?

soft shard
brittle haven
static matrix
#

any tips?

thin frigate
#

I'm trying to create an enemy spawner that creates a new instance of an enemy at a fixed rate. However, whenever I try to create a new enemy, the first one gets destroyed. Is there some functionality of Instatiate that I'm missing here?

#

public class DroneSpawner : MonoBehaviour
{
public GameObject enemies;
public GameObject drone;

float coolDown = 1.3f;

// Start is called before the first frame update
public void Start()
{
    Invoke("SpawnDrone", 2);
}

void SpawnDrone()
{
    GameObject newDrone = (GameObject)Instantiate(drone, enemies.transform);
    newDrone.transform.position = gameObject.transform.position;

    Invoke("SpawnDrone", coolDown);
}

}

buoyant crane
thin frigate
#

I think, hold on

#

yes

buoyant crane
leaden ice
#

Also your (GameObject) cast is unecessary

thin frigate
soft shard
# static matrix any tips?

The easiest solution might be to use a empty RectTransform as the parent, then you can sort the image and texts both as children - though if "InventBG" is the white square, it looks like another UI element or canvas is infront of it, unless your text color is meant to be grey

leaden ice
#

you must have some. What scripts does the prefab have?

thin frigate
#

`public class Drone : Enemy
{
int score = 100;

enum DroneState
{
    searching,
    mining,
    collecting
}

DroneState droneState;

// Start is called before the first frame update
protected override void Start()
{
    base.Start();
    droneState = DroneState.searching;
}

// Update is called once per frame
protected override void FixedUpdate()
{
    base.FixedUpdate();
}

public override void HasHit()
{
    Remove();
}

public override void Remove()
{
    GameManager.Instance.playerScore += score;
    CollManager.Instance.scope.Remove(gameObject);
    Destroy(gameObject);
}

}
`

leaden ice
#

Destroy(gameObject);

#

certainly looks like some destroy code

thin frigate
#

Remove is the only way to destroy it, and it's not being called

leaden ice
#

also !code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
#

Put Debug.Log in it

thin frigate
#

ColManager.Instance.scope is the list of all game objects that I'm using for collisions and stuff. Any time a game entity is destroyed, it should remove its reference from scope. That's what Remove is for. However, the issue I'm having is that Scope is being cluttered with null references, which should be impossible and is causing bugs.

#

if Remove was being called, the reference would have been removed from scope.

thin frigate
leaden ice
thin frigate
leaden ice
#

they will cause MissingReferenceException

#

If you have NullReferenceException it has nothing to do with objects being destroyed

thin frigate
#

Then I guess I meant MissingReferenceExeption

leaden ice
#

Don't guess

#

show your actual errors/error messages

thin frigate
#

I thought they were the same thing, appologies

leaden ice
#

show the full stack trace

#

(the preview section at the bottom of the console window)

thin hollow
#

Is there a way to know if the Animator's Controller is a controller itself, or an override of one? I'm trying to write a script for managing custom animations for stuff like weapons and scripted sequences by just having a few "generic" animations that I intend to dynamically swap during the game, with overrides, and RN it seems that on a startup it gets the initial animator from my character, and not the actual override controller I've assigned to it. So I want to include an "if" statement that checks whether it's an override or not there.

        public void Start()
        {
            animator = GetComponent<Animator>();
            
            RuntimeAnimatorController anim = animator.runtimeAnimatorController;

            animatorOverrideController = new AnimatorOverrideController(anim);
            
            animator.runtimeAnimatorController = animatorOverrideController;

            clipOverrides = new AnimationClipOverrides(animatorOverrideController.overridesCount);
            
            animatorOverrideController.GetOverrides(clipOverrides);
        }
slim spruce
thin frigate
leaden ice
#

maybe we can help

#

but without details, hard to help

thin frigate
#
cs
public static bool HasCollision(GameObject a, GameObject b)
    {
        //Missing Reference Preventers
        //if(a == null)
        //{
        //    Debug.Log("GameObject a was null");
        //    return false;
        //}
        //if (b == null)
        //{
        //    Debug.Log("GameObject b was null");
        //    return false;
        //}

        if (a == b) { return false; }

        CollisionBox aBox = a.GetComponent<CollisionBox>();
        CollisionBox bBox = b.GetComponent<CollisionBox>();

        float distance = (b.transform.position.x - a.transform.position.x)* (b.transform.position.x - a.transform.position.x) +(b.transform.position.y - a.transform.position.y)* (b.transform.position.y - a.transform.position.y);

        if(distance < Mathf.Pow((aBox.radius + bBox.radius), 2) )
        {
            return true;
        }
        return false;
    }
#

This is the code where the MissingReference is being thrown, in the collision checker.

#

Which makes sense, the collision checker loops through all objects in the scope and uses this to check if the two objects have a collision. The issue isn't that this method fails if there is a missing reference, the issue is that there should never be a missing reference

#

I was pretty sure that the issue must have been from some kink of the Instantiate method that I wasn't aware about, but if that's not it then I have absolutely no clue what could be causing this.

leaden ice
#

Otherwise, search your code for Destroy calls

thin frigate
#

The only other destroy that's not inside of a Remove method is in my singleton implementation

#
cs
    public void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(this);
        }
        else
        {
            Instance = this;
        }
    }
#

(This is in GameManager)

thin frigate
#
        newDrone = Instantiate(drone, enemies.transform);
        newDrone.transform.position = gameObject.transform.position + new Vector3(0,0,5);
#

Where newDrone is named in the class

sleek bough
#

Don't leave space before cs

leaden ice
candid kiln
#

where the hell is "gizmos"

thin frigate
leaden ice
candid kiln
#

thank you

sleek bough
candid kiln
#

aight

leaden ice
thin frigate
#

Remove isn't being called at all, I checked with Debug.Log

leaden ice
#

But you have multiple Remove implementations right?

#

On different enemies?

#

Drones are just one

thin frigate
#

This is the first enemy I've implemented

leaden ice
#

Here's a question

#

you're doing CollManager.Instance.scope.Remove(gameObject); in Remove

#

but where are you adding things to the scope?

#

I don't see that anywhere

thin frigate
#

In Start()

#
public abstract class GameEntity : MonoBehaviour
{
    [Header("GameEntity Vars")]
    public Vector3 direction = new Vector3(0, 0, 0);
    public Vector3 velocity;
    public float speed;

    // Start is called before the first frame update
    protected virtual void Start()
    {
        //Make sure that any GameEntity has a CollisionBox
        gameObject.GetComponent<CollisionBox>();

        //Add to Scope
        CollManager.Instance.scope.Add(gameObject);
    }

    // Update is called once per frame
    protected virtual void FixedUpdate()
    {
        transform.position += velocity;
        speed = velocity.magnitude;
    }

    public virtual void Remove()
    {
        CollManager.Instance.scope.Remove(gameObject);
        Destroy(gameObject);
    }
}
#

GameEntity is the parent class for anything that is in Scope

leaden ice
leaden ice
#

Also shouldn't you just do:

    public override void Remove()
    {
        base.Remove();
        GameManager.Instance.playerScore += score;
    }```
#

And can you show the code for CollManager?

#

Ideally in a pastebin site

thin frigate
thin frigate
leaden ice
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
#

any of those links

thin frigate
thick socket
#
 public Button BackgroundButton => _backgroundButton ??=
        _rootVisualElement.Q<Button>("backgroundButton");
private void Start()
    {
        _rootVisualElement = GetComponent<UIDocument>().rootVisualElement;
        _backgroundButton.clicked += () => buttonClicked();
        SpawnIn(40, GameManager.instance.playerInventory.WeaponList[0], 100);
    }```
error says _backgroundButton is not set to an instance...yet it should be...not sure if the _backgroundButton declaration is set correctly
#

does this code not actually set the private variable?

public Button BackgroundButton => _backgroundButton ??=
        _rootVisualElement.Q<Button>("backgroundButton");
leaden ice
thin frigate
#

PlayerController.FixedUpdate()

#

the type is Asteroids

leaden ice
thin frigate
#
        #region collisions
        if(CollManager.GetCollisionsByComponent<Astroid>(gameObject, out GameObject asteroid))
        {
            velocity = -velocity;
        }

        #endregion
leaden ice
thin frigate
#

They do, but they get Removed correctly

leaden ice
thin frigate
#

Yes

leaden ice
#

Can you show the asteroid code

thin frigate
#

Not Enemies specifically though

leaden ice
#

I didn't know there was a difference 😉

thin frigate
#

Yeah, I realize that in hindsight haha

#

Astroids are created in WorldBuilder

#

(Destructible is the type of GameEntity's that can be hit by player's bullets)

#

(This includes both Asteroid and Enemy)

leaden ice
#

you need to get to the bottom of this

#

Inside public static bool HasCollision(GameObject a, GameObject b)

thin frigate
thin frigate
#

Or am I wrong?

eternal geyser
#

hello i am new in this discord

leaden ice
#

scope should be private, and access to it controlled with public methods

#

in those public methods you can add more logging etc to see when things are being added and removed from the scope

#

that can give you some more insight into what's happening

thin frigate
#

This works fine:

#
    void SpawnDrone()
    {
        //newDrone = Instantiate(drone);
        //newDrone.transform.position = gameObject.transform.position + new Vector3(0,0,5);
        Instantiate(drone);

        Invoke("SpawnDrone", coolDown);
    }
leaden ice
thin frigate
#

That's what I had initially

eternal geyser
#

what does invoke mean

leaden ice
#

"run this function later"

eternal geyser
#

ou alright thanks

leaden ice
#

it's a poor man's coroutine

thin frigate
#

Or a lazy man's coroutine haha

eternal geyser
#

guys so this code is working perfectly fine, but do you think i could have done something better?

eternal geyser
thin frigate
#
    void SpawnDrone()
    {
        GameObject newDrone;
        newDrone = Instantiate(drone);
        newDrone.transform.position = gameObject.transform.position + new Vector3(0,0,5);
        //Instantiate(drone);

        Invoke("SpawnDrone", coolDown);
    }

This is broken again

eternal geyser
#

like how do you do that code thing

eternal geyser
#

ou sick thanks

thick socket
#

I favorited the gif 😄

eternal geyser
#

will do too now xD

eternal geyser
thin frigate
#

Ty

#

I just watched Helluva Boss last night actually

eternal geyser
#

ouuuu nice

thin frigate
#

I was not expecting to like it but

dusk apex
thin frigate
#

good show

eternal geyser
#

sorry i meant

thin frigate
#

That's probably a code-beginner question if I had to say

#

that channel's more active anyways

eternal geyser
#

yeah but like, is there any way i can save destroyed objects when switching scenes

#

then this way

eternal geyser
#

i mean i understand the code and made it somehow without tutorials

#

but does it really need to be like that

thick socket
lunar anvil
#

How can I turn on Tonemapping per code?

eternal geyser
#

thanks

#

for info

soft shard
# lunar anvil How can I turn on Tonemapping per code?

Through its volume profile, youd access or cache it with TryGet<T>, a simple example:

public class SomeScript : Mono
{
[SerializeField] Volume fx;

LensDistortion distort;

void Start()
{
fx.profile.TryGet<LensDistortion>(out distort);
distort.enabled = false;
}
}
thick socket
grim copper
#

Hi, I've got an enemy script and whenever the enemy attacks the player its gun rotates towards the player. I Want the robots hand (the one that is holding the grip/handle) to rotate along with the gun so it looks like the robot is actually holding the gun.

Here's my current code which doesnt work and creates really odd rotations

                Quaternion targetRotation = Quaternion.LookRotation(hit.point - attackPoint.position);
                enemyGun.transform.rotation = Quaternion.RotateTowards(enemyGun.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
                // Rotate the arm in the opposite direction of the gun
                Quaternion armRotation = arm.rotation;
                float gunRotationY = enemyGun.transform.eulerAngles.y;
                armRotation.eulerAngles = new Vector3(armRotation.eulerAngles.x, gunRotationY, armRotation.eulerAngles.z);
                arm.rotation = armRotation;```

here's my desired effect
#

i made those in the inspector ^

thick socket
#

idk if 3d you use the animator but I do it in the animator for things like that for 2d

grim copper
#

oh yeah

#

how would i make it so that the gun can only rotate 24 degrees max cuz in the pictures the gun is at 24 and -24 degrees i believe

#

i tried to and it didnt work

thick socket
#

if x>24, x=24
then rotate it maybe

grim copper
#

alr thanks

swift falcon
#

y does this not work? its not detecting the collisions.
im trying to check if the player(a cube) is colliding with the maze.

grim copper
dusty badger
somber nacelle
dusty badger
grim copper
#

I've got some faulty code, basically the gun rotates to the right and is clamped at 24 degrees like it should be, but bugs out going to a bunch of random numbers and like snapping back and forth.

            {
                // Rotate the gun towards the hit point
                Quaternion targetRotation = Quaternion.LookRotation(hit.point - attackPoint.position);
                enemyGun.transform.rotation = Quaternion.RotateTowards(enemyGun.transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
                
                // Limit the y-axis rotation of the gun to the range of -24 to 24 degrees
                Vector3 gunRotation = enemyGun.transform.eulerAngles;
                gunRotation.y = Mathf.Min(gunRotation.y, 24f);
                enemyGun.transform.eulerAngles = gunRotation; 
            }```

this code is just for an ai rotating a gun towards a player
swift falcon
somber nacelle
dusty badger
swift falcon
somber nacelle
#

then move on to the next step. there are many things you need to check and that site walks you through all of them

dusty badger
#

i might have messed that up honestly its been a while

somber nacelle
#

well for one you shouldn't be comparing a layermask to a layer directly like that

#

two, if you're going to use layers you might as well go all in with layer based collision rather than comparing the layer ints like that
and three, comparing tags works just fine if you do it right

dusty badger
#

yeah theres the bitshift stuff, same idea

#

thats not really relevant but if youre talking about best practices then you want to stay away from strings whenever possible

grim copper
somber nacelle
grim copper
#

i have no idea how i tried inverse kinematics but it made the robot one not work two all bendy

somber nacelle
grim copper
#

well what im really trying is to basically have the hand move along w the gun handle. I originally tried IK which failed and then realised that i could maybe clamp the gun to 24 degrees (this degree is the max you can go with both the gun and hand while looking accurate), and then i thought i'd move the hand along with the gun too but thats another thing i'll have to try to do

swift falcon
#

ok it kinda works now, that site was helpful

#

thx

elfin tree
#

Can anyone tell me what's null looking at this?

#

I've tried running debugging but everything seems fine..

#

Will keep on testing things unless someone has an idea!

#

Found it I think!

#

I wish it said which var it is..

neon plank
#

If I call a method with [WriteAccessRequired] inside an IJobParallelFor, what happens exactly? Is the method still called concurrently or Unity will schedule and execute the job in a way that it is only acceded once at the same time?

pale owl
#

I have an Audio Manager which holds multiple audio clips / audio sources to spawn and despawn whenever the sound is over.

I need a way to change the music in the audio manager whenever I change scenes and so I was wondering if I can somehow set the audio clip to = the audio source of an objecd named Music. So the audio managers SPECIFIC audio clip for playing music would only ever play the audio of the object Music that is in the scene.
Or if there's a code I can use to change the audio for "Music" in the audio manager

Does anyone know how I can do this or any alternative ways?
I havent been able to find the answer anywhere for hours. I feel like I've tried all I know to do it but I dont know enough.

#

LOL I've been looking through the old messages here to see if anyoen else had the same problem too but I havent found anything yet.

leaden ice
dusty badger
stable rivet
#

(i think, haven't had to do this with exceptions in a while & can't remember if IDE debuggers work the same in unity as it does other processes)

leaden ice
#

Debuggers don't stop on exceptions by default

#

But he knows which line it is so easy enough to drop a breakpoint

stable rivet
#

yup, would be my approach

pale owl
#

Because since it doesnt destroy on load, the audio stays the same.

#

If I were to Stop the music, I'd have to make an entirely new audio source in my audio manager which would mean I'd have like 120 different audio sources in my audio manager. But instead, what I had before I had my audio manager was I'd have an object in my scene which contains the music and plays the music attached to itself. But with the audio manager allowing the music to continue between scenes, I dont wanna lose that so I need a way to perhaps... ... Have an object (MusicObject). In that object is the audio and then set the audio clip in a separate object (Audio Manager) to be = to the audio of the first object.(Music Object).

That way the music wont change on load if the Music object in the scene is the same audio clip, but if its a different audio clip then audio manager will play the new one.

I'm not sure how to do that.

#

If anyone knows audio sources, audio clips or audio managers well, I can share my code. I just really need help 😭

dusty badger
#

im having trouble visualizing this system with the MusicObject so its hard for me to say, maybe someone will get it

#

i feel like you can just have all your audio in one place and then assign audiosource.clip whenever you need to, or dont

#

but again i feel like im just missing what youre trying to do

pale owl
#

Maybe I could idk XD

dusty badger
#

why do you have to make a new audio source?

pale owl
#

Because I have walking sounds, jumping sounds, landing sounds, attack sounds, enemy hit sounds, etc...

#

So the audio manager creates a new audio source and deletes it when the sound is complete

dusty badger
#

i need to stop answering questions on topics i havent worked on in a long time haha

#

but is it necessary to delete the audio source when the sound is done?

pale owl
#

OH wait no I'm saying that wrong

#

My bad

dusty badger
#

you could have a separate audiosource for the music maybe

#

and keep doing whatever youre doing for sounds

pale owl
#

It used to do that

#

Not anymore I got confused

#

So yeah, like you said, it creates all of the audio sources in the hierarchy as a child of AudioManager

#

Looks like this in the inspector

#

I need to find a way to change Clip (under the music at the bottom) when I change scenes to be a specific song for each of my scenes.

dusty badger
#

hmm that example is using a coroutine but i dont think its necessary

#

if you can access the audio source called "music" here at some point in your scene loading logic you should just be able to change the clip right?

#

maybe you have to call Stop() on the audiosource, assign the clip, then call play?

pale owl
#

I'm trying to think about how that would fit into my code. notlikethis

dusty badger
#

hmm well you have to figure out when you want one music to stop and the other play, is it right when you start loading, when loading finishes

#

to keep it simple, maybe just inside your "load scene" function, you assign the clip that you want there

pale owl
#

My biggest problem is figuring out how to get the clip from AudioManager's Music Sound's clip.

#

Thats hard to say

dusty badger
#

public function called SwitchMusic() that you call from the load scene function?

#

SwitchMusic() would be in the audio manager

pale owl
#

Thats helpful 🙌

#

Do you know how to call upon that specific clip?

dusty badger
#

where are you storing it?

pale owl
#

I'll send my code maybe

#

In Audio Manager

#

Script

dusty badger
#

do you have a List<AudioClip> in your audio manager?

#

and you are dragging and dropping all the audioclips from your assets into the inspector

pale owl
#

Yeah

dusty badger
#

then you have a reference to all the audioclips in audiomanager, so you could just do SwitchMusic(int musicIndexInList) for example

pale owl
#

OH! Wait do you mean, list all of them and then choose the int for example if music was 15???

#

Then change the audio clip for 15

dusty badger
#

yep that way the scene loader doesnt need a reference to the audioclip

pale owl
#

OwO

dusty badger
#

although you could also do it that way, you can make that list public and have the logic directly in the scene loader if you wanted

#

its just cleaner to have all that logic in the audio manager

#

and theres other ways to be cleaner too but you can clean that up later

pale owl
#

I think I know what to do then!!!

#

Thank you, I'll try something

paper heart
#

How to make c# errors in another thread be thrown into debug console?
because when error occurs there (for example, div by zero) the thread stops and it doesnt print anything into the console

dusty badger
#

they have to be in a try/catch block

#

im not sure if try/catch works in a thread you created yourself actually, if you use C# Tasks you can get the exceptions with try/catch

#

i havent seen if theres a method to automatically do it nowadays that popped up but when i checked a while back you had to do that

elfin tree
#

I instantiate the same Canvas prefab twice at runtime, one time it has the World Space property [1], which does not appear in the original prefab (which is the desired result, not sure why it works that way). In the second case, it stays as the prefab, with missing options in the Canvas component [2].

#

(click the images, not sure why discord sized them like that)

simple egret
#

Hm, maybe it doesn't show all options if the canvas is a child of another

#

Which would make sense as only the root can dictate where it's placed and how it's rendered

solemn raven
#

hi,
is it possible to hide/show some properties on the editor based on enum or a bool ?

simple egret
#

If you have NaughtyAttributes, you can use a conditional attribute. Else, make your own custom inspector

elfin tree
solemn raven
simple egret
#

NaughtyAttribute's docs, online

solemn raven
latent latch
#

I suggest just using naughty's

#

There's a lot of attributes among the conditional attribute that you'll find useful

#

That and it does supply you with some functionality for custom inspector stuff if you do want to create some later

elfin tree
#

Anything wrong here at first glance?

#

I guess I'll order them in paint, Discord messes it up.

simple egret
#

Canvas positions should be set using the RectTransform's anchoredPosition, so your anchoring preset is respected

elfin tree
#

I'll check, better version (since i already did it)

simple egret
#

(Discard if the target position is translated from world space to screen space)

elfin tree
#

Btw I call it an anchor but it's not really one

#

Not sure if relevant

#

But those are all transform.position

#

It's the whole canvas that's moving

simple egret
#

You'll have to explain what you want to do, and what those variables are

elfin tree
raw relic
#

Hi, I have a simple question: I have a player with a Rigidbody which in turn has multiple colliders under it (a few for general collision and one to check if it's feet are grounded). I want to know which one of the colliders was hit in OnCollisionEnter(Collision collision). Looking at collision.collider is not right since it's just the thing I'm colliding with, not my own collider. Do i really need to give each collider a separate kinematic Rigidbody and MonoBehaviour just to know which collider generated the event?

elfin tree
#

I guess my thing is hard to understand as is, will keep on testing things!

#

I think all it was was me changing .position instead of .localPositon

dusty badger
#

or iterate through all the contacts

raw relic
#

@dusty badger Ah thanks! I've always just assumed GetContact was to get a basic Vector3 impact point for some reason. I usually don't work too much with gameplay code 😅

thin frigate
#

What is the best way to debug how a certain list in my code is losing references to game objects?

graceful rampart
#

hey so I just updated my game to newest version of unity and now Im just getting this error message and dont know what it means or how to fix it

thin frigate
#

I have a "scope" list in my GameManager containing all active game objects of a certain type, and for some reason it keeps losing references to one specific type of game object shortly after they're instantiated. I'm not familiar enough with VisualStudios debugging, help would be appreciated.

graceful rampart
raw relic
#

Algo 3602 Ah thanks I ve always just

warm wren
# graceful rampart

I think u can just ignore that, u can restart the editor if u want and it only really becomes a problem if it continues to come back

graceful rampart
#

ya ive restarted multiple times and its been happening for a few days now

#

i cant delete the line of code or anything either

warm wren
#

Have u tried deleting your project's library folder?

graceful rampart
#

i have not

#

ill try that

#

it just gave me more errors and it replaced it automaticly

#

i can ignore it but idk if it will mess with when I finish a build of the game