#archived-code-general

1 messages ยท Page 206 of 1

rancid frost
#

thats due to mesh.clear above

#

๐Ÿ™‚

#

so the mesh is definietly, being modified

swift falcon
#

yeah, i was changing it in the code like a dumbass

hybrid turtle
#

hey does anyone know if you can buffer the drag speed of a slider?

#

I have a slider controlling an animation and need it so people can't blast through

#

has anyone also made like a slider to control the point in time an animation is at

#

Im not sure if it's as simple as this

#
{
    private PlayableDirector playableDirector; 
    [SerializeField] private Slider timeScrollerslider; // retrieve the slider component from the gameObject
    private float animationDuration; 
    void Start()
    {
        playableDirector = GetComponent<PlayableDirector>(); 
        animationDuration = (float) playableDirector.duration; 
    }

    void Update()
    {
        playableDirector.time = animationDuration * timeScrollerslider.value; // call in update every frame? 
    }```
neon plank
#

Is this how would you consume an IAsyncEnumerator in a coroutine?:

IAsyncEnumerator<DigimochiNFT> digimochisProducer = DigimochiNFT.GetAllDigimochis().GetAsyncEnumerator();

while (true)
{
    ValueTask<bool> task = digimochisProducer.MoveNextAsync();
    while (!task.IsCompleted)
        yield return null;

    ExceptionDispatchInfo exception = null;
    try
    {
        if (task.GetAwaiter().GetResult())
            digimochis.Add(digimochisProducer.Current);
        else
            break;
    }
    catch (Exception e)
    {
        exception = ExceptionDispatchInfo.Capture(e);
    }

    if (exception is not null)
    {
        ValueTask disposeTask = digimochisProducer.DisposeAsync();
        while (!disposeTask.IsCompleted)
            yield return null;
        try
        {
            disposeTask.GetAwaiter().GetResult();
        }
        catch (Exception e)
        {
            throw new AggregateException(e, exception.SourceException);
        }
        exception.Throw();
    }
}

{
    ValueTask disposeTask = digimochisProducer.DisposeAsync();
    while (!disposeTask.IsCompleted)
        yield return null;
    disposeTask.GetAwaiter().GetResult();
}
tender gull
#

Hi.. I've got a little problem with Singletons between Scenes..
my setup is that each scene needs some managers that are singleton classes (like AudioManager, CameraManager etc.), some of those should live between scenes. Eg. I'm on some portion of map and ofter player reach some point I want to load new part of map and unload old ones. I add to them DontDestroyOnLoad so their work won't be interrupted (eg. global audio like music won't cut off).
The problem start if I'll try to keep those manage systems also on those other scenes (eg. for testing) - what's the best way to takle that problem?

I tried to create one super-manager that has other managers underneath (at least those that need to be kept between scenes) and if he sees other super-manager (from newly loaded scene) destroyes itselt, but it feels overcomplicated and doesn't solve anything (I don't know how, but those 'destroyed' managers still exists and try to receive inputs etc.)

normal hedge
#

I am having the following issue:
I have a Script attached to a object that holds a reference to its own Transfrom.
When I Instantiate that object, that reference moves with the new Instance.
(The new instance is now holding a refence to itself)
Is there a way to stop that behavior?
My goal is to keep the reference to the original while instantiating.

somber nacelle
#

have whatever instantiates the object pass the reference to the prefab back to the instantiated object. but why would it need that reference in the first place?

normal hedge
#

Ill take a look if I can do that (thinking about it, should be quite clear to implement (hopefully)).
The reason it has that reference is that this is a wave function collapse based Terrain gen, each tile holds its valid neighbours which in some cases includes themself.
However the way I collect and process these neighbours neccesitates the reference to the original

heady iris
#
playableDirector.time = Mathf.MoveTowards(playableDirector.time, timeScrollerslider.value, Time.deltaTime);
#

this would go from 0 to 1 in one second

hybrid turtle
#

ok ok ill give it a shot and see if it smoothes the transition

#

clamps it too much

#

what i was thinking

#

is make a float buffer

#

like 0.80 then multiply that into animationDuration * timeScroller.value * buffer

#

probably will have a more controllable effect

hybrid turtle
#

hey guys can you swap a texture in unity at runtime

#

?

#

I have four different textures and would like to swap them out at runtime

dusky lake
hybrid turtle
#

material

#

I want to access these materials from the MeshRender

#

and change the textures within them

#

is this possible?

dusky lake
#

You can either create 4 materials and swap those

hybrid turtle
#

yeah I dont mind doing that

dusky lake
#

or swap the keyword "_MainTex" on the material directly

hybrid turtle
#

hmm

#
        meshRenderer.material.SetTexture("_BumpMap", NormalMapTexture);```
dusky lake
#

Yeah same for maintex

hybrid turtle
#

i saw this online you can get the component and call setTexture

#

but idk if it works for smth other than the normal

#

as shown here

dusky lake
#

but be advised, you are changing the material instance with it, it might affect other objects

hybrid turtle
#

so basically every object with that material assigned will have its texture changed?

dusky lake
#

i am not sure right now under which circumstances, but yes that can happen

#

your best bet would imo be to just swap between materials

#

instead of editing one material

hybrid turtle
#

the thing is i have scripts

#

that depend on the materials whose textures I am changing

#

and if i swap the materials there I'd need to swap them on all my acting scripts

#

which is why I wanted to try with textures first and brings me to a bit of a conundrum

dusky lake
#

The short answer: Then edit the materials
The long answer: Thats keeping state in the wrong place, create a state-holder script instead of reading from materials in other scripts

hybrid turtle
#

ok ok I'll do a refactor then

#

thank you

rancid frost
#

does anyone know why changing the vertices and triangles in a mesh doesnt show in the game?

#

I am trying to add vertices and triangles to a mesh, and even do the respective arrays have increased in size, the mesh remains thesame

patent hound
#

odd question, in unity you can't create a copy of a component like you can a gameobject can you?

patent vector
#

Hello. When running my game in the editor, FPS slowly drop over time, bottoming out around ~32. Then if I pause the editor and wait a few seconds, when I hit play it goes back up to ~72 fps. Slowly drops again, pause resets, forever

#

I've explored the Profiler but can't see any obvious culprits in there... any ideas?

patent hound
#

I have run into a very weird coding case where i need to essentially copy the box collider from a child object to a parent object

rancid frost
patent vector
#

@rancid frost Seems like a likely culprit yeah, but it's almost more like garbage pileup? Cause of the gradual nature over time, until the pause.

patent hound
patent vector
#

Or maybe GC isn't running for some reason?

#

@patent hound You mean on my OS level, or w/i unity?

patent hound
#

like the ram usage of unity within your OS

rancid frost
dusky lake
patent vector
#

@rancid frost I'm not seeing anything unsual in the profiler. Cause it's not really spikes

#

Not even seeing anything increase over time in there

rancid frost
rancid frost
patent vector
#

@patent hound That's interesting. Looking now, nothing is increasing in RAM or CPU. But it does jump to using ~240% CPU while it runs... I wonder if my Mac is throttling it? Never had anything like that but could be

rancid frost
#

its ur code

dusky lake
patent hound
dusky lake
# rancid frost

Oh nvm, meshFilter.mesh outputs a copy of the used mesh, reapply it to use the changes

rancid frost
#

strangely, the triangle count of the scene goes up accordingly....

#

but the vertices dont....

patent vector
#

@patent hound What sort of virtual memory settings were you tweaking? It definitely seems to be some OS level issue, I'm running another very simple project now and seeing the same behavior

#

@rancid frost It's not the code, ^^

patent hound
#

I was trying to see how slow certain things would be on a system with less ram so i changed the virtual and physical memory settings in windows

patent vector
#

Don't love the implications of my machine just slowing down.. maight need some fan cleaning

patent hound
#

it was not a unity setting i tweaked

rancid frost
patent hound
#

sanity check here, does this code snippet work as described

#

//now we need to make a new box collider that encapsulates this object and the weapon inside //create a new box collider and bounds BoxCollider newBoxCollider = this.gameObject.AddComponent<BoxCollider>(); Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); //check if we have a renderer and encapsulate it to start with if (transform.GetComponent<Renderer>() != null) { Renderer thisRenderer = transform.GetComponent<Renderer>(); bounds.Encapsulate(thisRenderer.bounds); } newBoxCollider.center = bounds.center - transform.position; newBoxCollider.size = bounds.size; //iterate through the children of this object //the weapon and other object we need for our purposes will have renderers on layer 1 so we do not need to iterate through all of their children foreach (Transform childTransform in gameObject.GetComponentsInChildren<Transform>()) { Renderer childRenderer = childTransform.GetComponent<Renderer>(); //if that child has a renderer encapsulate it if(childRenderer != null) { bounds.Encapsulate(childRenderer.bounds); } newBoxCollider.center = bounds.center - transform.position; newBoxCollider.size = bounds.size; }

patent vector
#

@rancid frost Yes it's having the same behavior in a completely fresh/empty project

rancid frost
#

I dont know how to be of assistance

#

perhaps, u got some other program fucking with you?

#

check vsync maybe

#

that could be it

rancid frost
patent hound
#

I wanted to ensure that the center and size were never null so i left the first one out of the if statement

#

however they don't need to be reset in the for loop you are correct

rancid frost
#

newBoxCollider.center = bounds.center - transform.position;

#

if the collider is on the transform, why subtract transform position?

dusky lake
# rancid frost any ideas?

Have you tried all that in a sample manner? If the vertex count changes it sounds like the error might be somewhere else in the code

patent hound
#

good catch

rancid frost
dusky lake
#

ill test some and then report back

cosmic rain
rancid frost
#

the first time I add a new set of vertices, it shows

#

after that nothing

rancid frost
rancid frost
cosmic rain
#

This is creating a new mesh. Are you using this method to modify it as well?

rancid frost
#

no

rancid frost
cosmic rain
#

For starters, I'd avoid relying on the statistics window. It's known to produce unreliable information for debugging.

#

You should step through your code, or inspect the relevant objects in the inspector. You can also see rendering info in the profiler.

cosmic rain
dusky lake
cosmic rain
# rancid frost

Check the triangles array. Does it contain the new vertex indices?

dusky lake
#
using UnityEngine;

public class TestScript : MonoBehaviour
{
    public MeshFilter Filter;

    public void Update()
    {
        if (!Input.GetKeyDown(KeyCode.A)) return;

        var mesh = Filter.mesh;
        var vert = new Vector3[mesh.vertices.Length];
        for (var index = 0; index < mesh.vertices.Length; index++)
        {
            vert[index] = Quaternion.Euler(45f, 0, 0) * mesh.vertices[index];
        }

        mesh.vertices = vert;
        Filter.mesh = mesh;
    }
}
rancid frost
cosmic rain
#

Did you have a look at the mesh in the inspector?

rancid frost
#

uh

rancid frost
#

nothing much

cosmic rain
# rancid frost

Not the frame debugger. Just double click the mesh in the mesh filter

cosmic rain
#

Does it update?

rancid frost
#

wait I know why

#

the triangles

#

it must be relative

cosmic rain
#

relative to what?

rancid frost
#

mesh A was 3 vertex

#

triangles are 0 1 2

#

mesh B had 3 vertex

#

triangles are 0 1 2

#

if u merge them...

#

Mesh B triangles are not 3 4 5

cosmic rain
#

Merging meshes? I don't remember you mentioning that. But that might explain many things.

cosmic rain
rancid frost
#

i was checking if they werent empty ๐Ÿ˜ฆ

dusky lake
#
        private void LateUpdate()
        {
            if (!_changeDetected) return;
            if (!Follow) return;
            if (Vector3.Distance(_targetFollowPoint, _currentFollowPoint) < 0.1f)
            {
                _changeDetected = false;
                return;
            }

            var cameraTransform = transform;
            _currentFollowPoint = Vector3.Lerp(_currentFollowPoint, _targetFollowPoint, LerpAmount);
            var rotation = Quaternion.Euler(Angle);
            var offsetPosition = _currentFollowPoint + rotation * new Vector3(0, 0, -Distance);

            cameraTransform.position = offsetPosition;
            cameraTransform.rotation = rotation;
        }
rancid frost
somber nacelle
#

obligatory "use cinemachine"

rancid frost
rigid island
#

probably not since this script is inLateUpdate

rancid frost
#

wtf

dusky lake
rancid frost
somber nacelle
dusky lake
#

Never touched it, guess i have some documentation to watch

rigid island
rancid frost
rancid frost
rancid frost
rigid island
dusky lake
#

I am stupid, made the recheck distance to big

Anyways, now that it runs smoothly, lets remove it all and implement cinemachine ๐Ÿ˜„

rigid island
#

its butter smoooth

#

don't even get me started on Impulse/noise

#

extra butter

rancid frost
dusky lake
#

Anyways, before asking questions, I should look at the feature to begin with ๐Ÿ˜„

rigid island
dusky lake
#

eh, then i might aswell have an empty transform target

rigid island
#

usually people do that , call it like "cinemachineTarget" or w/e

#

because some of the camera modes are affected by the target's rotation

dusky lake
#

and let cinemachine handle everything for me ๐Ÿ˜„

#

aight, you got me convinced, already in love with it ๐Ÿ˜„

rigid island
#

My favorite part is Auto Blending between cams and also when I make a game in old Resident Evil style it has a camera auto camera switching when you're in range of certain cams

cosmic rain
inner yarrow
#

Does OnTriggerStay2D stop getting called if the object it's on isn't moving?

inner yarrow
# spring creek Nope

Hmm, I don't know what's wrong then, but I think I found a workaround so I should be fine.

rancid frost
bronze hemlock
#

anyone know how to stop a charactercontroller bouncing when going down a slope?

oblique spoke
tired jay
#

why is my code not changing color. it works but if i make a mistake in writing the code there are no red wiggly lines which makes it harder to write code if i make a small typo. is my visual studio missing something

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

tired jay
patent hound
#

i suck at quaternions, is there a good way to put an object 1 unit in front of the player but only factoring in the y rotation?

#

essentially i want to place the object 1 unit in front of the camera but not factor in the up/down rotation of the camera, only the left right rotation

somber nacelle
#

you don't need quaternions for that so i'm not sure why you prefaced your question with "i suck at quaternions"
you should be able to project the camera's transform.forward onto a plane with a normal of Vector3.up using the Vector3.ProjectOnPlane method

#

you may need to normalize the resulting Vector3 from that to get it exactly 1 unit away though

patent hound
#

i was not aware of the projectonplane method, i thought i was gonna have to do some quaternion math

urban owl
#

how to run video recorder on Built game?

somber nacelle
#

like the Unity Recorder from Window > General > Recorder? because that's editor only

#

also not a code question

urban owl
#

Window > General > Recorder? yes

somber nacelle
#

if that is the recorder you are referring to, then it does not work in a built game. it is editor only

urban owl
#

how to record video on game?

somber nacelle
#

like just record your game window? that's not a unity question. nor is it a code question. but you can use software like OBS to do so

urban owl
#

I want to make a video player, to play mp4 and mp3 voice

#

and record that video

somber nacelle
#

why are you using a game engine to do that

urban owl
#

I don't need this one, what else can I use

somber nacelle
#

why don't you do some research and find a tool that makes more sense to create a video player/recorder app in?

urban owl
#

because I can use AI in unity

somber nacelle
#

so your video player is also going to incorporate AI? or are you referring to using AI to help you make it because you don't actually know what you are doing?

urban owl
#

AIGC things

#

I can do it in editor now, but I want run it on website

somber nacelle
#

well the recorder i mentioned earlier would not be appropriate for what you are trying to do because it doesn't do that. nor would unity be a good choice for creating a video player app

patent hound
#

i have been struggling to understand the projectonplane function for like 2 hours lol, and after not getting it for around an hour i've started toying with it as a gizmo drawline and i'm now more confused

#

i'm using code similar to

#

cameraWorld = gameObject.GetComponent<Character>().GetCameraWorld(); Transform cTransform = cameraWorld.transform; Gizmos.DrawLine(transform.position, Vector3.ProjectOnPlane(cTransform.forward * 1, Vector3.up);

#

but i've tried switching the variables around, changing what i'm putting in the function and i am just not getting the results that are coming out

#

it's the fact that it isn't (vector, plane) that's confusing me, it's 2 vectors and my brain is just farting out getting what the second vector does

somber nacelle
#

if you read the docs, you'll see that the second parameter is the normal for the plane. you don't need to define a whole plane for it, it just needs the normal for the math it does. your parameters for the method are correct. although i don't see why you've multiplied the cTransform.forward by 1. you do know that multiplying anything by 1 is just going to return itself, right? so that's a pointless operation

patent hound
#

well it had a variable for distance there originally and i've just been changing small details one after another, simply did that instead of deleting it

somber nacelle
#

okay so what is it currently doing that you are not expecting?

patent hound
#

it's shooting a line off at a 45 degree angle that stays the same in world space regardless of what direction the camera is facing

#

you can see the gizmo line shooting off the player in the same direction even though i've rotated nearly 180 degrees

somber nacelle
#

remember that the second parameter for Gizmos.DrawLine is the end position. not the direction.

#

you're getting the camera's forward direction projected on the plane with the Vector3.up normal. if you use that as a position it's going to be within 1 unit of the scene origin

patent hound
#

well i had it as transform.position + the current projectonplane but that does other wild unpredictable things

somber nacelle
#

try it now

patent hound
#

you're right though that doesn't make sense the way i had it in that code snippet since it's not position,angle it draws the line between 2 positions

#

i got it figured out FINALLY it was because i wasn't spawning them far enough from the player object their rigidbodies were freakign out forcing them through the ground

#

making me think that the spawning was going the wrong direction and spawning them down

idle flax
#

How can I make this work? I want other scripts to be able to call this function, inputting another function of their choosing.

public void AddAction(Action action)
    {
        GameObject instantiatedAction = Instantiate(actionItem, transform.position, Quaternion.identity);
        instantiatedAction.transform.SetParent(contextMenu.transform);
        instantiatedAction.GetComponentInChildren<TextMeshProUGUI>().SetText(action.ToString());
        instantiatedAction.GetComponent<Button>().onClick.AddListener(?)
    }
prime sinew
#

That's the type that onClick takes

idle flax
#

Thanks

summer estuary
#

is it possible to run a unity api call as a coroutine? i need to recalculate the collider for a large tilemap, so i'm using a composite collider and calling GenerateGeometry(), but it hangs the frame for a moment. is there a way that i can make that function call run like a coroutine?

#

eg. StartCoroutine(collider.GenerateGeometry());

mellow sigil
#

That's not how coroutines work. If you call a method in a coroutine it'll hang just the same as when called anywhere else

#

To avoid that you'd need to run it in another thread

summer estuary
#

hmm that probably won't work since unity api calls have to be on the ui thread right?

#

maybe i should investigate more efficient collider options

vivid remnant
#

I created a procedural door mechanism that allows me to add/remove another door as a pair for the one that is already present inside the scene. When I add a door, everything works as expected but when I remove it, the mesh of the original door disappears and only reappears once I hit Ctrl+Z. The doors were created using Probuilder. Please watch the video in order to get a clearer picture of the problem.

Does anybody have any idea what could be the potential cause for this issue?

worn wyvern
#

Is there a way to make this method show up in the Unity UI? I guess it won't show because of the enum ScoreSource

public enum ScoreSource { None, Bumper, Rollover, Slingshot }

public void AddScoreWithSource(int amount, ScoreSource source)
{
  score += amount;
  Debug.Log($"Add {amount} to score from {source}, netting {score} total score");
}
vivid remnant
# vivid remnant I created a procedural door mechanism that allows me to add/remove another door ...

Here is the source code:
https://pastebin.com/4wvm3bRT - Mechanism
https://pastebin.com/NJ85VkuT - Editor Mechanism

oblique spoke
worn wyvern
oblique spoke
patent hound
#

Is there a simple debugger I can do within unity to see what accesses the setActive function of a gameobject? Something is clearly interfering with my ability to set a gameobject to active properly and im trying to figure out what script is causing it

worn wyvern
#

Oh yeah right, though it would defeat what I'm trying to achieve here

#

I guess I could do it in two methods, SetSource and then AddScore

#
public void SetSource(ScoreSource source)
{
        
}

Damn this won't even show up in the event UI, guess enums are not handled

vivid remnant
oblique spoke
worn wyvern
#

@oblique spoke I did understand what you meant... and it's alright!

#

Not as pretty as directly setting the arguments in the event UI directly, but that's alright!

#

Thanks ๐Ÿ™‚

#

Is it required to mark public fields with [SerializeField] ? or is it the norm now?

oblique spoke
upper ice
#

Hi

#

What is the difference between Convert and Parse?

quartz folio
#

Provide some context. They are words

true bramble
#
public class Entity : MonoBehaviour
{
    // Start is called before the first frame update
    private Rigidbody2D rb;
    public float speed = 3f;
    void Awake()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    public void Move(int amount)
    {
        rb.AddForceX(speed*amount);
    }
}```
Why does Awake from base class never get called if I am doing something like this
```cs
public class Player : Entity
{
    int input()
    {
        return Convert.ToInt32(Input.GetKeyDown(KeyCode.D)) - Convert.ToInt32(Input.GetKeyDown(KeyCode.A));
    }

    // Update is called once per frame
    void Update()
    {
        //Input.GetKeyDown(KeyCode.E)
        Move(input());
    }
}
knotty sun
heady iris
#

i guess that gives you a value between -1 and 1

true bramble
heady iris
#

Are you getting an exception when you try to use rb?

rigid island
true bramble
heady iris
#

I am not clear what this means.

#

"it doesn't see it"?

#

what are all of these "its"?

quartz folio
heady iris
#

Convert only contains a few Try* methods

knotty sun
true bramble
heady iris
#

if it doesn't, then you probably have a compile error that's preventing anything from updating in the first place

true bramble
heady iris
#

Did you mean that the rb field says "None (Rigidbody2D)"?

#

you can check if Awake is running by logging something in Awake

quartz folio
#

If it says None then that gameObject didn't have a Rigidbody2D on it

true bramble
#

im attaching the Player class to the object though

heady iris
#

Show the inspector.

true bramble
#

hmm its working now

#

this is wack

wary coyote
#

Before I even try, how easy / hard / impossible would it be to make a component that runs on update that imitates the Symmetry behaviour pictured here? Context that is 3dsmax.

#

Is this something totally nontrivial and I shouldnt even attempt it? Or do you imagine its very do-able? Maybe a stock asset in some github exists with this done already?

rigid island
#

maybe UModeler X does it?

wary coyote
wary coyote
#

looking at it it doesn't feel impossible, the two things happening is its cloning the mesh along an axis, which feels simple, and unions them if they intersect on that axis, which feels way harder to do

#

Oh interesting, that does appear to be what I was looking for, Ill google what this UModeler X package is

rigid island
wary coyote
# rigid island true. true. anything is possible with enough knowledge ๐Ÿ˜›

๐Ÿ˜ sure that answer is technically correct but it doesnt answer the spirit or intent of my question. It kind of hurts to be given such a pedantic reply.
the real question that we both know I was asking is how difficult will this be, am I going to go into development hell and become immensely frustrated by repeated failures to achieve this effect because I don't realize how challenging its going to be

rigid island
#

Yeah I suppose so.
Thought you were looking for assets that does it similar thing instead of wanting to write the whole feature.
Sorry its all I got

wary coyote
#

I apologize as well I was not clear

#

If no stock asset exists I was going to try to write it myself

knotty sun
wary coyote
#

Why do you have to fight me instead of just answering the question? Sorry I even asked

#

I dont understand why developers find it so incredibly important to attack and challenge anyone who reaches out for help instead of fostering a welcoming and supportive environment

rigid island
#

maybe you're just taking things a little too personal or as implied criticism lol

#

I can't speak for others but I have really bad people skills, but I do wanna help

heady iris
#

I do not know how hard it would be. To me, it looks like the main challenge will be slicing the mesh along the plane of symmetry.

#

The rest is trivial.

#

(perhaps other than welding vertices together at the plane of symmetry, if you need that)

#

After you cut the mesh across the symmetry plane, you just need to reflect all of its vertices across the plane. That's basic math.

#

I suppose you'd also need to flip all of the normals, since the winding order would be backwards.

heady iris
knotty sun
heady iris
#

it's easy to decide if each vertex should be kept, but producing new vertices to replace those that got chopped off sounds a little harder.

latent latch
heady iris
#

I would expect there to be at least one mesh manipulation package that can do this kind of thing.

#

There are quite a few for doing runtime object shattering, for example

rigid island
heady iris
#

Cutting an object in half is the hard part of this problem

rigid island
#

Umodeler X does all this in editor

#

if only we can find the source code

tawny yacht
#

Idk what i imported but i got this Asset Unlock - 3D and now my game is broken. how do i go back?

thick terrace
rigid island
#

u can just delete the Asset Unlock - 3D

tawny yacht
#

some of my layers got removed. and if i delete the folder the materials dont show and it turns pink

tawny yacht
rigid island
#

you probably imported the project settings too

tawny yacht
#

yeah

rigid island
#

which you should probably not have done

tawny yacht
#

this was a months work

#

is there a way to go back

rigid island
#

You don't have a commit?

tawny yacht
#

i do

rigid island
#

so revert

tawny yacht
#

but as i said the materials

#

will revert too no

rigid island
#

wasnt materials working when you made committ

tawny yacht
#

no only scripts

#

maybe i copy the textures and materials folder

rigid island
#

so you never made a proper commit ?

#

with materals and textures

heady iris
tawny yacht
#

no i was using URP

rigid island
#

or otherway around

tawny yacht
#

the project now looks at the new URP for some reason

heady iris
#

Select one of your materials that is broken and show me the inspector.

tawny yacht
rigid island
#

you Imported Project Settings when youimported asset so it changed everything, double check what Graphics settings your project has

heady iris
#

yeah, let's see what the project settings look like

tawny yacht
#

hmmm

#

i put urp and now the materials show

#

but some of the layers are gone too

#

that was a big part in the scripts

heady iris
#

The layer numbers will not have changed

#

just the name of each layer

#

you can reassign them pretty easily

tawny yacht
#

yea thanks

#

i can figure out from here

heady iris
#

use proper version control to prevent this in the future

tawny yacht
#

on it

acoustic sinew
#

I decided to try and play with a new movement system today using the character controller. I'm trying to use the .isGrounded but for some reason it's not seeing that my player is grounded and my player is floating in the air by .02

#

Using Debug, when the player is standing still it shows controller.isGrounded to be false, however when I start moving the player is flips between true and false

#

I am using the network manager to spawn in the player

acoustic sinew
#

Well now it is showing true for isGrounded, but only when the player is moving

#

Shouldn't it still show "True" even when the player is sitting still?

rigid island
#

hold up, let me check my crystal ball

#

๐Ÿ”ฎ

#

ball says : Depends

leaden ice
#

so it's generally annoying to use

#

and doesnt work in a lot of situations

#

most people implement their own grounded check

acoustic sinew
#

So even if the move command is used, but the player doesn't actually move, it doesn't matter. The player has to physically move for it to check

rigid island
#

isGrounded is limited af

#

use an overlaps or cast

deft jungle
#

I have List<Transform> TopPatrolPoints initialized in inspector. When I try to debug. log this.TopPatrolPoints[0].position.x (line 103) I get error: MissingReferenceException: The variable TopPatrolPoints of Bartek doesn't exist anymore.
You probably need to reassign the TopPatrolPoints variable of the 'Bartek' script in the inspector.

swift falcon
#

If anyone got a simple pistol script that shoots and stuff dm me it for Unity VR

somber nacelle
swift falcon
somber nacelle
#

chill it was an answer to your question

#

if you want to not be lazy and actually put in literally any amount of effort to make your game, then i suggest you watch some tutorials or something. there are plenty that go over how you can make a weapon

swift falcon
#

A no would work ๐Ÿ’€

craggy crest
#

Quick question: I wanna freeze my Z position in 2D movement. I wanna do it by: The declaration is at the top of my class and the target transform in my update method

#
target.transform.position.z = 0.0f;```
#

It gives me an error and says: "The return value of Transform.position is not a variable and therefore cannot be changed"

#

Then I tried to store it in a Vector3 variable but it didn't do the job either

#

Like that: private void Start() { Vector3 lockedZpos = transform.position; lockedZpos.z = 0; target.transform.position = lockedZpos; }

#

And set the lockedZpos.z 0 in the Update method

fervent furnace
#

dont cross post, but you have already post the errors here
start only runs once, you should put it in update

craggy crest
#

Any ideas?

rigid island
craggy crest
#

I did now, but still doesn't do the job

craggy crest
rigid island
craggy crest
#

Oh it's complex ๐Ÿ˜…

#

I am doing a game where you can switch between 3D and 2D

#
{

    [SerializeField] private Transform target;

    [SerializeField] private MouseSensitivity mouseSensitivity;

    private Vector2 _input;

    private float _distanceToPlayer;

    [SerializeField] private CameraAngle cameraAngle;
    private CameraRotation _cameraRotation;

    bool use2DPerspective = false;

    private void Awake() => _distanceToPlayer = Vector3.Distance(transform.position, target.position);

    public void Look(InputAction.CallbackContext context)
    {
        _input = context.ReadValue<Vector2>();
    }

    private void Update()
    {
        _cameraRotation.yaw += _input.x * mouseSensitivity.horizontal * Time.deltaTime;
        _cameraRotation.pitch += _input.y * mouseSensitivity.vertical * Time.deltaTime;
        _cameraRotation.pitch = Mathf.Clamp(_cameraRotation.pitch, cameraAngle.min, cameraAngle.max);

        if (Input.GetKeyDown(KeyCode.C))
        {
            use2DPerspective = !use2DPerspective;
            Camera.main.orthographic = use2DPerspective;

            if (use2DPerspective)
            {
                Vector3 lockedZpos = transform.position;
                lockedZpos.z = 0;
                target.transform.position = lockedZpos;
                mouseSensitivity.horizontal = 0;
                mouseSensitivity.vertical = 0;
                Camera.main.transform.eulerAngles = new Vector3(transform.rotation.x, transform.rotation.y, transform.rotation.z) * 0;
            }
            else
            {
                mouseSensitivity.horizontal = 20;
                mouseSensitivity.vertical = 20;
            }
        }
    }```
#
    {
        if (use2DPerspective == false)
        {
            transform.eulerAngles = new Vector3(_cameraRotation.pitch, _cameraRotation.yaw, 0.0f);
        }

        transform.position = target.position - transform.forward * _distanceToPlayer;
    }
}

[Serializable]
public struct MouseSensitivity
{
    public float horizontal;
    public float vertical;
}

public struct CameraRotation
{
    public float pitch;
    public float yaw;
}

[Serializable]
public struct CameraAngle
{
    public float min;
    public float max;
}```
rigid island
rigid island
#

hmm yeah thats gonna give you weird jitter iirc

#

also why not Cinemachine lol

#

2 cameras. . job done

craggy crest
#

Movement which works in 2D and 3D

rough tartan
#

hello, so i'm currently working on a multiplayer system, so I made this code that work with my serveur with web socket. This code work fine but the problem is that I can't have more than 2 player connect at the same time because the code decript all the message he received and applied all of them to one player so if the data come from 2 different player the ennemie player in your game will applied to himself 2 diffรฉrent location, So I wanted to know what will be the best way of making the multiplayer work with more than 2 people , how I can and what's the best for making an instance for each player based on their ID that the serveur give me and apply for each of them specific value like their coordinate or if they receid damage...?
(sorry for my bad english ๐Ÿ˜… )

waxen kayak
#

Does anyone have any ideas on why there is never a tile found?

 if(gridManager)
            {
                Vector3Int pos = Vector3Int.FloorToInt(HitPosition.position);
                Debug.Log(pos);
                Vector3Int cellpos = gridManager.waterMap.WorldToCell(pos);
                Debug.Log(cellpos);
                Tile tile = gridManager.waterMap.GetTile<Tile>(cellpos);
                if(tile != null)
                {
                    Debug.Log(tile.name);
                }
#

There is a tile where the position is, there is a gridmanager, so I don't know

craggy crest
waxen kayak
rigid island
waxen kayak
craggy crest
rigid island
#

and with that is very simple.

leaden ice
#

You should do WorldToCell directly on HitPosition.position without any transformations

waxen kayak
#

Yeah that might have been the problem

#

but I don't see why that would be

leaden ice
heady iris
#

maybe it put you under the floor

#

Flooring is always wrong here, because tiles aren't necessarily aligned to a 1x1 grid

waxen kayak
#

yeah but the water is a LOT of water, so even if it would get moved out it would still be in a water tile

heady iris
#

i'm thinking about the third dimension

waxen kayak
#

hmmm

sharp lotus
#

hey gang im having issues applying a knockback to rigidbodies where if i shoot a corner it gets knocked back and properly twists in a realistic way, as it stands it seems its applying the force to the center of the game object regardless of where i shoot

#

this is how im applying the force
hitRigidbody.AddForce(mainCamera.transform.forward * bulletKnockback, ForceMode.Impulse);

waxen kayak
#

AddForceAtPosition

#

with the direction being the same as you do now

#

the position the hit position

sharp lotus
#

testing

waxen kayak
#

literally just joined to ask a question

heady iris
#

This will allow you to apply a force to an object somewhere other than its center of mass

waxen kayak
#

Inferior formal answer

heady iris
#

oh, I completely glossed over your answer lol

#

๐Ÿง  โšก

#

zap

sharp lotus
#

oof this may be more complicated than expected. cause im saving all the hit objects into an array on shoot and processing them after the shooting/damage/bullet decals happens

heady iris
#

well, you just need to remember the hit point

waxen kayak
#

you can save a raycastHit[]

sharp lotus
#

ye, probably save it along with the object

waxen kayak
#

can't you?

heady iris
#

If you currently store a single Vector3 for the force or something, just replace it with a struct that holds all of the data you need

heady iris
waxen kayak
heady iris
#

I know you can get punked if you try to re-use Collision objects, because that's a class, not a struct

#

unity will reuse the same object for every collision message

waxen kayak
#

well it's worth a try, @sharp lotus , do it for science

rigid island
sharp lotus
waxen kayak
#

my god

waxen kayak
rigid island
#

oh wops m bad I just saw it now

#

my internet delays sometimes

#

mcdonald quality wifi

sharp lotus
#

oh im dumb lmao.. im saving the list of hit objects like so
hitObjects.Add(hit.transform.gameObject);
only need to remove everything after "hit" LOL

heady iris
#

right, that would store the entire RaycastHit

sharp lotus
#

its still acting the same

#

should i mess with these

waxen kayak
#

show us the code

#

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

sharp lotus
waxen kayak
#

Did you reload the scripts?

#

oh

#

you doN't need to use hit.transform.position

heady iris
#

oh yeah

waxen kayak
#

I think that's the transform of the hit object

#

you need to use point

heady iris
#

that's probably center of mass

sharp lotus
#

oh true

waxen kayak
#

I mean hit.point

heady iris
#

indeed

#

(or, at least, something vaguely close to center of mass, and something that doesn't depend on the point you hit)

sharp lotus
#

thanks gang

waxen kayak
#

๐Ÿ‘

soft ruin
#

hey so my the first line is correctly instantiating the game object but it is not setting the refrence

GameManager.Instance.activePlayer = Instantiate(playerPrefab, transform.position, playerPrefab.transform.rotation);
GameManager.GameEvents.onPlayerSpawned.Invoke(GameManager.Instance.activePlayer.transform);

the error is
NullReferenceException: Object reference not set to an instance of an object

#

anyone go any ideas why this is not working

waxen kayak
#

this is way too little context

soft ruin
#

how much more do you need

waxen kayak
#

For example: where is the error

#

which line

soft ruin
#

the error is caused on the first line

#

mb

waxen kayak
#

Then playerPrefab is missing, or gamemanager is

soft ruin
#

playerPrefab is not missing

#

let me check game manager

#

game manager was

waxen kayak
#

yeah

soft ruin
#

tyty

heady iris
#

which line is the error on?

#

oh, scrolled back

#

bah

waxen kayak
#

This is so funny

heady iris
#

discord scrollback gets me again

knotty sun
# deft jungle Any ideas?

Add a player ID to your WebSocket messages then only process the messages if the ID matches the current player

deft jungle
#

It's not multiplayer game

fair bane
#

Hi. I just started learning unity 1 week ago, and I wanted to make a flappy bird game. I already have the bird movement, but I just need to spawn the pipes and make them move. Can you help me do it pls?

waxen kayak
#

there are literaly hundreds of online resources on that

somber nacelle
#

there are plenty of tutorials for flappy bird games in unity, you should go check some out

fair bane
#

Can you recommend me one?

#

Because I didn't understand some of them

somber nacelle
#

then you should start by learning the basics. there are beginner c# courses pinned in #๐Ÿ’ปโ”ƒcode-beginner and the pathways on the unity !learn site are a good place to start learning the engine

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

waxen kayak
#

https://youtu.be/hKGzSYXPQwY This seems quick and seems to do the job

Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Wishlist Veil of Maia! - https://store.steampowered.com/app/1948230/Veil_of_Maia/

Make flappy bird with this quick Unity tut...

โ–ถ Play video
knotty sun
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.

deft jungle
#

Here it is

knotty sun
#

Man, do you not understand 'correctly'? Use a paste site

deft jungle
#

oh, sry

#

here is the link

#

And here is the problem:

#

I have List<Transform> TopPatrolPoints initialized in inspector. When I try to debug. log this.TopPatrolPoints[0].position.x (line 103) I get error: MissingReferenceException: The variable TopPatrolPoints of Bartek doesn't exist anymore.
You probably need to reassign the TopPatrolPoints variable of the 'Bartek' script in the inspector.

knotty sun
deft jungle
#

It's not this, I've commented the line and I still get the error

knotty sun
#

@deft jungle Why did you do this?

try
{
      matrix.GetComponent<Enemy>().abc = this.TopPatrolPoints[0]; ;
} catch(System.Exception e) {
      Debug.LogWarning(e.Message);
}
#

note you have one ; too many

deft jungle
#

; was accident

#

probably after deleting code

knotty sun
#

this is code. accidents can be fatal

#

but I meant the try catch block

wanton crest
#

Hi
I'm the other guy working on that game, came in to see what can be done

wanton crest
#

The one Darthspartan is seeking help for

knotty sun
#

so explain the try catch

wanton crest
#

I'd personally pick a more specific one, though I haven't set this one up

craggy crest
wanton crest
#

the way I left it the script all this runs in was used for an entirely different thing, hence the Destroy(this);

rigid island
#

locking z sometimes is just as simple as locking the target

deft jungle
# knotty sun but I meant the try catch block

abc is Transform ans I check whether I can set a Transform type variable from here, this works: Debug.Log(this.TopPatrolPoints.Count);

this doesn't:
Debug.Log(this.TopPatrolPoints[0].position.x);

shell scarab
#

is this something I need to fix from code when instantiating a prefab that has a camera with a stack?

#

what it looks like normally:

craggy crest
#

whatever, i'll try

shell scarab
#

yes

rigid island
#

what does Fix do

shell scarab
#

im not sure. Fixes it.

#

but the top is during play mode

#

after instantiating the 2nd prefab

knotty sun
shell scarab
#

i'm using it for a screen space UI for a split screen game

rigid island
shell scarab
#

The UI is on the player prefab and is set to Screen Space - Camera. The camera in the stack is to render it over everything, i's an overlay camera.

knotty sun
#

@deft jungle What I dont understand is why you have a try catch block and even if it fails you carry on regardless

rigid island
shell scarab
#

ye

#

it's like it's getting "confused" on which camera to render to or something maybe

#

but im not sure how to fix that or if thats even a coding problem.

deft jungle
knotty sun
#

where?

deft jungle
#

I've just done it

rigid island
shell scarab
#

maybe?

#

I mean it's split screen so shouldn't be right

deft jungle
shell scarab
#

maybe I'll just add it to the stack in awake and see if it fixes

#

does anyone know how to access those modules from c#?

#

that didn't work. I wonder what "output properties" it's talking about. Maybe if I could find out I could copy the values over to the overlay camera.

#

it must have something to do with it being split screen

latent latch
#
    public static void DrawLines(Vector3 position)
    {
        material.SetPass(0);

        // Set transformation matrix for drawing to
        // match our transform
        Matrix4x4 transformationMatrix = Matrix4x4.TRS(position, Quaternion.identity, new Vector3(1, 1, 1));

        GL.PushMatrix();
        GL.MultMatrix(transformationMatrix);

        GL.Begin(GL.LINES);
        GL.Color(UnityEngine.Color.white);

        foreach(GridLine line in lines)
        {
            GL.Vertex(line.PointA);
            GL.Vertex(line.PointB);
        }

        GL.PopMatrix();
        GL.End();
    }

Any idea why setting a 4x4 TRS matrix here and then drawing isn't being drawn in the right place? However, if I do a translation matrix and translate each point it works, but that's just a lot of extra work I don't think needs done.

rigid island
#

which modules are you talking about ?

polar marten
#

do you have a link or a screenshot to your game as is?

muted root
#

Hello i need a small suggestion, in my game i need some way to get the current Real Time (like DateTime.now) but the problem with that is cheating ๐Ÿ˜ฌ since someone can just change the date on his pc and fake the date.
i was thinking of using Cloud Code from UGS to take one time the realTime from a unity server, would that be fine? or is there another better way of doing it?๐Ÿค”

deft jungle
leaden ice
latent latch
#

I was thinking that I should translate the matrix after calling GL.Vertex

#

the position I set here doesn't change the position of where I make these vertices or at least I'm guessing

rigid island
#

no need to do cloud code and waste your free/paid tier w unity

muted root
rigid island
#

can depend on so many things..

#

size of assets being one

#

also not a code question

lethal vigil
river copper
#

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

haughty harbor
#

Is it normal to have so much shaderlab files when uploading onto github?

leaden ice
#

If not then no

#

my guess is your .gitignore was not set up properly

#

and you probably uploaded your Library folder

haughty harbor
haughty harbor
leaden ice
#

ยฏ_(ใƒ„)_/ยฏ

#

just look at your repo

#

see what's in it

haughty harbor
#

After making a new scene :/

haughty harbor
leaden ice
#

at the project root

#

but you need to do this first:

just look at your repo
see what's in it

haughty harbor
leaden ice
#

if so then that's fine

haughty harbor
#

yeh

haughty harbor
dire marlin
#

PlayerPrefs aren't loading in my Awake() function when i load a scene, how do i fix?

leaden ice
dire marlin
#

i use a simple system to check what checkpoint player is to be teleported

rigid island
leaden ice
dire marlin
rigid island
#

you want to make sure that works first, then move onto saving / loading

rigid island
unreal thorn
#

Does anyone know why the code in the void Setup would not be working?

rigid island
#

working would be you actually calling the method

unreal thorn
#

So I would have to call the setup thing?

heady iris
#

methods don't call themselves

unreal thorn
#

but Update does?

heady iris
#

There is a very specific set of methods that will be executed by Unity in various situations

night harness
#

Technicially Editor related but wasn't sure if my question was generic enough to slide in here, VS is telling me my second return is unreachable code? I'm trying to make this editor related function safe to reference in non editor scripts

    public static IEnumerable<ValueDropdownItem> GetScriptableObjects(Type type)
    {
#if (UNITY_EDITOR)
        List<ValueDropdownItem> newScriptableObjects = new List<ValueDropdownItem>();
        IEnumerable<ValueDropdownItem> scriptableObjects;

        scriptableObjects = UnityEditor.AssetDatabase.FindAssets("t:ScriptableObject")
        .Select(x => UnityEditor.AssetDatabase.GUIDToAssetPath(x))
        .Select(x => new ValueDropdownItem(x, UnityEditor.AssetDatabase.LoadAssetAtPath<ScriptableObject>(x)));

        foreach (ValueDropdownItem item in scriptableObjects)
        {
            if (item.Value.GetType() == type)
                newScriptableObjects.Add(item);
            else if (item.Value.GetType().BaseType != null && item.Value.GetType().BaseType == type)
                newScriptableObjects.Add(item);
        }
        return (newScriptableObjects);
#endif
        return (null);
    }
heady iris
#

They are all listed here, in the "Messages" section

#

It sounds to me like you want to use Awake or Start.

unreal thorn
#

Okay, yeah. Idk why it works for her in the tutorial video ๐Ÿ˜ญ

heady iris
#

Perhaps something else calls the Setup method.

#

it would have to be something in the same class, since it's private

night harness
heady iris
#

what tutorial is this?

heady iris
unreal thorn
# heady iris what tutorial is this?

In this video, will be coving setting up an inventory UI in the scene. You'll learn how to add UI elements to the canvas and reference UI elements in code.

Support me on Patreon: https://www.patreon.com/jacquelynneHei
Follow me on Twitter: https://twitter.com/JacquelynneHei2
Join the Discord: https://discord.gg/e3N9mbBRhR

Cozy Farm Asset Pack:...

โ–ถ Play video
heady iris
#

(along with a bunch of very useful timing information)

heady iris
#

bingo

night harness
#

Randomly jumped to 7:59 and found your issue, Missed a line ๐Ÿ˜„

unreal thorn
unreal thorn
#

I had legit just assumed it was a function like start

frigid bone
#

Hello , does anyone know how to add a material onto a meshrenderer during runtime? (Add - not change)

leaden ice
#

naturally you'll need to make an array that is one larger than the existing array and add your new material as the last element

frigid bone
#

Something like:

        foreach(SkinnedMeshRenderer rend in Highlightmeshes)
        {
            Material mat = rend.material;
            rend.materials = new Material[2];
            rend.materials[0] = mat;
            rend.materials[1] = HighlightMaterial;
        }

?

leaden ice
#

more like - get the existing array

#

make an array that is one larger

#

put your material at the end of the new array

#

write the new array back

leaden ice
frigid bone
#

The unit is modular , so theres 6 skinmeshrenders on one creature , thats why that is there.

#

And no this didnt work

leaden ice
#

I told you it wouldn't work

#

you didn't do it properly

#

you need something like this:

Material[] mats = rend.materials;
Array.Resize(ref mats, mats.Length + 1);
mats[^1] = HighlightMaterial;
rend.materials = mats;```
frigid bone
#

Alright so... Get - resize - set.

Gotcha , lets see this in action

#

Voila , worked wonders

#

Thank you very much

leaden ice
#

you specifically can't do rend.materials[0] = mat; because rend.materials returns a fresh copy of the array every time you call it

#

so not only is it very wasteful - it doesn't do anything

frigid bone
#

Ahh gotcha. So i wasnt doing much with my first attempt

#

Is that the case with all get/set?

#

For future cases

heady iris
#

Not generally. I guess most things aren't returning arrays, though.

leaden ice
#

It's the case for MANY array properties in Unity though

#

because they often are copying data over from the C++ side

heady iris
#

yeah

#

they aren't giving you direct access to the memory used by the C++ side

frigid bone
#

Ohh so they are being cautious on this particular thing ?

heady iris
#

I mean, there's no way you could do that without using unsafe code

#

(like, literally using an unsafe block)

leaden ice
heady iris
#

Almost everything on a unity object that looks like a field is really a property

#

This comes up a lot more often with stuff like this

unreal notch
heady iris
#
transform.position.y += 1;
#

This does not work because transform.position is a property that returns a vector3

#

so you'd be setting the y value of the returned struct, which is useless

frigid bone
#

Yeah it says it right there in the docs , i really should read those more when i get stuck

heady iris
#

It's not intuitive, but now you know :p

frigid bone
#

Well you learn something new everyday ๐Ÿ˜› , Thank you both

zinc parrot
#

Is there an easy way to save the values in a component I modify during play back to editor?

rain minnow
zinc parrot
#

but I may modify like 30 different gameobjects

rain minnow
#

then that won't work. why do you need to keep the changes to 30 GameObjects during runtime?

zinc parrot
#

because im basically modifying a non-unity material
so I am in play to see how it looks(needed), but I want it saved after I exit

rain minnow
#

oh, well i don't know what non-unity material is or means. sounds tricky . . .

zinc parrot
#

basically just treat it as a script with a bunch of publc floats inside that I wanted saved

west lotus
# zinc parrot basically just treat it as a script with a bunch of publc floats inside that I w...

Cinemachine have a completely generic SaveDuringPlay attribute implementation that I dont inow why isnt part of the core engine by now https://github.com/Unity-Technologies/com.unity.cinemachine/blob/main/com.unity.cinemachine/Editor/SaveDuringPlay/SaveDuringPlay.cs

GitHub

Smart camera tools for passionate creators. Contribute to Unity-Technologies/com.unity.cinemachine development by creating an account on GitHub.

zinc parrot
#

OOO thank you so much!!!

pure scarab
#

How to layer noise caves on top of an already existing mesh?

river copper
#

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

tranquil canopy
#

Hey, how could i give unity location permissions?

#

just like in Android

#

is that possible?

mellow sigil
#

Does your computer have a GPS receiver?

tranquil canopy
#

hmm, not really know

mellow sigil
#

That was a rhetorical question

#

Phones know their own location because they have GPS. Computers do not.

#

There are online services that guess the location by IP address but that's not very accurate

tranquil canopy
#

oh

#

and another question, is there any way to see console logs once the game is builded on android?

tranquil canopy
#

does someone know why it show me this message when i try to see logs in my android game from computer?

dense swan
#

hello, when we move file in our project folder from directory to another or rename them, unity will move them and re link the assets and the items used on the scene and stuffs. Is there a way to do that operation using code? Is it safe to just copy them manually using operating system's file manager? (like windows explorer)

fervent furnace
#

i remember you can just install logcat in unity editor without using cmd

#

if you need terminal, then the logcat ui also provides a button to open terminal

stiff saddle
#

Is this the right channel to ask why my autocomplete stopped working for unity stuff?

fervent furnace
#

!ide probably your code editor is updated (or something else) so it stops working

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

stiff saddle
worn night
#

Sometimes you need to restart the code extensions within unity

#

Edit, preferences, external tools

#

Regenerate project files with the right external script editor

#

In your case VSCode

stiff saddle
#

Hmm it was already set to vscode and so the button didnt change anything

vivid remnant
#

Is there a way to create a method similar to OnControllerColliderHit() but that only gets called when the Character Controller enters a collision?

stiff saddle
#

I also tried installing like all the unity related extentions which didn't work lol

worn night
stiff saddle
worn night
#

:( Then I don't know, I use rider for this stuff

#

Or visual studio

vivid remnant
#

I mean making a method that acts similarly to OnCollisionEnter() but for a Character Controller.

worn night
#

You can do something like

OnCollisionEnter(Collider other) {
if (other.TryGetComponent<CharacterController>(out var controller))
 // Do stuff with controller
}
stiff saddle
worn night
#

If I understand correctly what you are trying to do ๐Ÿค”

worn night
#

So yeah ๐Ÿ˜”

stiff saddle
#

Alright, good to know!

#

I'll consider it :)

worn night
#

๐Ÿ™Œ

#

Good luck

vivid remnant
worn night
#

As far as I know the only way to do that is via C# events or Unity Events. You cannot modify or create new functions inside the Physics simulation environment tho :(

#

So you have to stick with the OnColliderEnter / Stay / Exit

vivid remnant
#

I see. Oh well, it would have been great thou. :)))

#

Thanks, @worn night!

worn night
#

Yeah... But oh well, good luck with the project you are doing ^^

#

And no worries!

odd crypt
#

Setting a MaterialPropertyBlock works in editor runtime, but not in build (Win10), what could it be?


Debug.Log("<color=blue>" + _rendererMapper.Renderers.Length + " renderers</color> on " + transform.name + ", queued " + _shaderPropertiesToApply.Count + " properties");
foreach (var renderer in _rendererMapper.Renderers)
{
    renderer.GetPropertyBlock(_propertyBlock);
    foreach (var propertyToApply in _shaderPropertiesToApply)
    {
        Debug.Log("<color=orange>SetFloat </color> " + propertyToApply.PropertyIdentifier.PropertyName + " " + propertyToApply.ParameterValue);
        _propertyBlock.SetFloat(propertyToApply.PropertyIdentifier.Hash, propertyToApply.ParameterValue);
    }
    Debug.Log("<color=magenta>Applied</color> MPB to " + renderer.name + ", isEmpty: " + _propertyBlock.isEmpty + ", materials: " + renderer.sharedMaterials.Length);
    renderer.SetPropertyBlock(_propertyBlock);
}
#

The debugs seem to indicate everything's in order, how to debug it further?
Also made sure the PropertyIdentifier.Hash is correct, as it should be or it wouldn't work in editor either

stiff saddle
#

@worn night Update: Apparently I had to update the Visual Studio package from the package manager

#

Seems illogical considering I wasn't using VS, but I'm not complaining because VS was so ugly I couldn't stand it anyways

patent kiln
#

where should i go for performance/profiler issue?

sly crag
#

Hey guys, what's the best way to store images locally in mobile, with or without a database

rain minnow
glad briar
#

Hi everyone, I need your help, I have a problem when I change the scene; I currently have 2 scenes named MainMenu and Game, when I launch the scene game I don't have problem but when I start MainMenu and switch to Game a light problem appear, some warning appear with shader problem with this text: The tree TFF_Birch_Tree_01A must use the Nature/Soft Occlusion shader. Otherwise billboarding/lighting will not work correctly. but this warning appear only when I switch scene, did someone know how to resolve this problem?

odd crypt
# odd crypt The debugs seem to indicate everything's in order, how to debug it further? Also...

I figured this out for anyone interested, I was calculating the property hash in OnValidate, since it only run in editor the hash wasn't being recalculated when running the build
Each name of shader property (for example, _MainTex or _Color) is assigned an unique integer number in Unity, that stays the same for the whole game. The numbers will not be the same between different runs of the game

dim hinge
#
logic = GameObject.FindGameObjectsWithTag("Logic").GetComponent<LogicScript>();```
the ide give me an error with ".GetComponent<LogicScript>();", why?
potent sleet
#

Can we use from clause in Unity no problem?

quartz folio
dim hinge
potent sleet
plucky fulcrum
#

Anyone know why a json save file has it's data reset sometimes when restarting my computer

hard viper
#

How does it work to have kinematic rigidbodies that donโ€™t just go through walls? I see a lot of people using kinematic rbs for characters, and just have to wonder: how do you make it actually โ€œcollideโ€ with shit properly?

#

as in, not fall through floors, get pushed by walls etc

#

I see that I really need a big degree of control over my character, and I keep fighting the physics system with dynamic RBs. So I think I need to bite the bullet and go towards a kinematic RB

potent sleet
hard viper
#

i see. that seems like doing the physics simulation myself, right? Iโ€™m wondering how it deals with constraints. Because if I have one block going into another block, if block1 casts to stop at block2, then block2 casts to stay put, that has a different result than the reverse order. Right?

#

but I guess everything finds a stable configuration in the end with no overlapping colliders?

#

actually, I wonder if I can replace moving transforms blindly with that cast? As in, instead of transform.Translate, I instead Cast, find distance, then move by that much.

hard viper
#

Thanks. I saw that before, but Iโ€™m still thinking.

#

I can make one dynamic rb player ride a platform (with only a little jank).

#

The issue is I actually have multiple dynamic RB blocks, where blocks can ride blocks, can ride blocks, and be in each otherโ€™s reference frames, which is when it breaks. Because Iโ€™m moving transforms.

#

Iโ€™ll need to check KCC again. ty

#

Maybe one more thing that might help: Is there a way to do casts that only search for compatible force receive layers? I have overrides, and I could check manually, but there are some cases where my framerate would be crippled if I have a Cast that returns a bunch of colliders from which we donโ€™t receive force

hard viper
potent sleet
inner yarrow
#

Ugh, I finally figured out why my guy would stop taking damage if he wasn't moving. His rigidbody kept sleeping on the job.

heady iris
#

When you launch a scene directly in the editor, it'll generate some stuff automatically

#

this won't happen when you load a scene

glad briar
#

Ok i gonna check, thx for the reply

vivid remnant
#

How can I make a Kinematic Rigidbody "push" a Character Controller?

spring creek
vivid remnant
#

Oh, raycasts. Sounds performance heavy.

leaden ice
#

raycasts are not performance heavy.

#

But if you want that kind of behavior you're better off using a Rigidbody controller

#

otherwise you'll have to do all the physics yourself

vivid remnant
#

I did it up until now. My character scripts are almost complete.

vivid remnant
#

I have some interactive objects on the map(doors and elevators, mainly) and I want them to be able to move the character.

glad briar
hearty sphinx
#

is this where i ask about testing?

#

i didn't find a specific channel for it

#

i'll ask anyway, is there a way to add the assemblycsharp dll to a test so i can reference it?

hearty sphinx
#

i've been looking around and it seems testing is hard ?

#

at least preparing and referencing them

#

if you have scripts in different folders, you have to reference everything separately

#

and you can't reference assembly csharp

#

even if you create an assembly definition in the asset folder, it doesn't reference the scripts in subfolders

#

even if you reference your local scripts, if those scripts reference something like textmeshpro or unity.localization, you'll get a lot of errors because they're not referenced for some reason

thick terrace
#

if you want the easy option you can just throw the tests in an Editor folder without an asmdef i think? you don't need to create a test assembly

#

then they'll be included in the Assembly-Csharp-Editor dll and you won't need to set up any references

hearty sphinx
#

how about play mode tests?

thick terrace
#

yeah you do need a test assembly for those

hearty sphinx
#

i can create a regular nunit project and reference the assembly csharp project normally

#

maybe play mode needs you to create an assembly for script in different folders? i don't get it

thick terrace
#

yes if you need to reference game code i think you'd have to make an assembly definition for that and reference it

hearty sphinx
#

oh well

#

who tests those anyway mad

hard viper
#

does Start() just wait for all pending Awake calls to be resolved?

rigid island
#

don't think start waits for anything related to other scripts

#

afaik they all run independently

#

eg, 2 scripts with Update never Update at same time

hard viper
#

but if I instantiate a prefab, all of its components call Awake, then OnEnable, then Start, right?

#

so one component's Start won't get called while we are waiting for all the other components to get their awake? I think?

rigid island
#

i think they only follow their execution order and don't care about other components

hard viper
#

I'm not sure that makes sense, because then Start can get run to reference something that isn't initialized yet, right?

rigid island
#

isnt that what happens though most of the time you put init code in Start?

#

thats why Awake is better cause it happens on all scripts before they run their own start

#

i think depending on also if object is active first or not

dusky cloak
#

Hey, so, I am making a game like "Scrap Mechanic", where you can connect objects and make "circuits", but, I don't really know how to make an "overlap" effect on the objects, like it happens on the game

(in the image, orange and green circles)

How can I make an approach to that effect?

rigid island
#

since they have 3D to them I'm gonna guess meshes

#

it can be replicated though fairly easy

dusky cloak
#

it would be like a gizmo

rigid island
#

the image you shown has disk shape / cylinders

dusky cloak
#

can be any of them

#

just for showing them it's enough

#

sorry for don't explaining much XD

rigid island
#

ideally you want to use a material you can see above any other objects

dusky cloak
#

yeah

rigid island
#

luckily you can easily do that with Render Features

dusky cloak
#

yeah, it's exactly what i want

rigid island
#

all you need to do is spawn that object / disk shape to where your points are

dusky cloak
#

thank you :D

eager steppe
#

is using a foreach loop in a if statement that is checked every frame a bad idea for performance and shit?
The code:


if (MusicSpeaker.time >= (Notes[CurrentTimeStampIndex].SpawnTime - timeToReachTarget) + (NoteSpawnOffset / 1000))
                    {

                        //it only checks the first one instead of progressing
                        Debug.Log("[GAME DEBUG] Game should create a note, before this event, and remove it from the list");
                        foreach (Tracks track in TrackedTracks)
                        {
                            if (track.TrackID == Notes[CurrentTimeStampIndex].Track)
                            {
                                Tracks[Notes[CurrentTimeStampIndex].Track].SpawnBeat(Notes[CurrentTimeStampIndex]);
                            }
                        }

                        CurrentTimeStampIndex++;
                    }


glad briar
hard viper
#

thatโ€™s good to know. I was mostly wondering about instantiation. Like, if I do;
Instantiate(PrefabWithComponent1);
doSomething with Component1;

Like, in the same line. Would Component1.Start() be done by the time I hit that second line?

stark sinew
#

If you do something like

thing.DoSomething();```
It's possible that `Start` didn't get called in between (I don't know about `Awake` but I think that one should always run)
#

That's something I've encountered in my current project, but I solved it easily by calling my own Initialize method before DoStuff, I'm trying to avoid relying on Awake/Start/OnEnable etc as much as possible

hard viper
#

Awake and OnEnable definitely are done

#

wasnโ€™t sure about start

#

OnEnable is weirdly fast as fuck

#

I also use an Initialize method sometimes, when I need the intermediate speed

glass berry
#

Using a wrapper class to run edge-playback using windows natural voices. Does microsoft have any libraries for tts that use the natural narrator? Else I'll need to use mpv with edge-playback through wrappers which is awful

stark sinew
# hard viper I also use an Initialize method sometimes, when I need the intermediate speed

What I'm doing is something like that

[SerializeField] private bool _AutoInitialize;

private void Start()
{
  if (!_AutoInitialize) return;
  Initialize();
}

public void Initialize()
{
  ...
}

That way, the stuff that gets spawned dynamically will have it's Initialize called by some other Script, but if I want to quickly test some functionality I can drag and drop a Prefab and tick AutoInit

glass berry
#

I know microsoft has speechSynthesis but that is the default narrator

#

I need to know if there's a win11 library for the natural narrator

hard viper
hard viper
glass berry
#

no problem

stark sinew
pale ore
hollow sluice
#

Is it possible to disable eventsystem to disable UI buttons and then enable eventsystem?

soft shard
hollow sluice
#

Okay, to be honest, I'm modding the game and I have a problem: when the UI is turned on, my custom UI works, and when the game's UI is turned off, it doesn't work, do you know why?

#

its something with InputSystem/EventSystem

leaden ice
#

If you disabled the event system, UI isn't going to work

heady iris
#

assuming the game object you're instantiating is active, and that the component is active and enabled, respectively

hollow sluice
#

the problem is that the game somehow disabling the UI interaction when its not used

hollow sluice
#

that making a big problem

heady iris
#

Start will not run until the next frame.

rigid island
#
for (int i = 0; i < fishes.Length; i++)
        {
            var randTarget = positions[Random.Range(0, positions.Count)];
            var routine = StartCoroutine(MoveFish(fishes[i], randTarget));
            fishesInCoroutine.Add(fishes[i], routine); // dictionary <Fish, Coroutine>```

Is this the right way to do this with coroutines ?  It's not working for some reason not stopping
#
 public void StopMovingFish(Fish fish)
    {
        Debug.Log(fish.name);
        Debug.Log(fishesInCoroutine[fish]);
        StopCoroutine(fishesInCoroutine[fish]);
    }```
heady iris
#

what if you start moving twice?

leaden ice
heady iris
#

you'll get an exception on the second attempt to call Add in that case

rigid island
rigid island
leaden ice
heady iris
#

what if you run the code up top twice before you call StopMovingFish?

#

actually

rigid island
#

the code ontop is in Start currently

heady iris
#

your code would start throwing errors after one round of moving fish -> stop moving fish

#

ah, okay

#

you should make sure you're stopping different fish each time, then

rigid island
heady iris
#

I don't see any reason for it to fail when just looking at that code

#

so I'd need to see more context

rigid island
rigid island
heady iris
#

the fish appear to be moving many times

#

not just once

#

so are you starting a new coroutine after reaching the target?

#

if so, your original coroutine is now irrelevant

rigid island
#

possible..

leaden ice
#

well what does MoveFish do

heady iris
#

hence why i wanted to see code

rigid island
#

Ahh shit I think its this
private void FishDestReached(Fish fish)
{
StartMovingFish(fish);
}

leaden ice
heady iris
#

which is a separate mechanism entirely from how you do it in Start

rigid island
# leaden ice why not just put a loop inside the coroutine

here is my whole func

IEnumerator MoveFish(Fish fish, Vector3 target)
    {
        while (Vector3.Distance(fish.transform.position, target) > 0.1f)
        {
            float T = 2 * Time.deltaTime;
            fish.transform.position = Vector3.MoveTowards(fish.transform.position, target, T);

            var dir = (target - fish.transform.position).normalized;
            if (dir != Vector3.zero)
            {
                Quaternion targetRotation = Quaternion.LookRotation(dir);
                fish.transform.rotation = Quaternion.Slerp(fish.transform.rotation, targetRotation, 2 * Time.deltaTime);
            }

           
            yield return null;
        }
        FishDestReached(fish);
        yield return null;
    }```
#

dont mind the bad lerp plz

#

just testing

leaden ice
#

so it continues forever

heady iris
#

yes

#

or, at least, make sure that FishDestReached updates the coroutine dictionary

#

I'd just make Start call StartMovingFish and then make StartMovingFish correctly track the coroutine

rigid island
leaden ice
#
while (true) {
  while (fish is not at its target) {
    MoveTowardsTarget();
  }

  PickANewTarget();
}
rigid island
#

ahh thats clean

heady iris
#

or if you want to be funny: yield return MoveFish(fish, PickTarget());

#

you can yield another IEnumerator

rigid island
heady iris
#

if you yield an IEnumerator, unity will call MoveNext on it every frame (or based on what you yield return from it) until it's exhausted, then resume calling MoveNext on you

#

I don't think it'd be very intuitive here, though.

#

It's a neat way to "compose" several iterators

rigid island
#

I think i accidentally done that pattern before in the past

heady iris
#

you can also yield return literally whatever you want and unity won't complain

#

yield return "hi"

rigid island
#

slowly got less afraid of while loops after doing console rpg :p

#

while loops everywhere

heady iris
#

I heavily used enumerators to create abilities in an RTS

#

I haven't nested them too much though

rigid island
#

I only used IEnumerator in unity ๐Ÿ˜ญ

#

just found out about IAsyncEnumerable a few days ago

heady iris
#

IEnumerator<T> is the generic flavor of that

#

so an ability might be a method returning IEnumerator<AbilityStatus>

#

it could indicate that it's busy or that it failed

rigid island
heady iris
#

IEnumerator just yields object

rigid island
#

which part of it did unity change just the yeild types?

heady iris
#

well, you can yield anything you want from an IEnumerator

#

Unity uses non-generic enumerators in several places

#

I don't think you could even create a type that meaningfully covers all of the things you can yield for a coroutine

#

C# does not have union types (booooooooo)

heady iris
rigid island
#

is that why you can do foreach on it ?

hollow sluice
heady iris
#
foreach (var thing in transform)
#

thing will be object

simple egret
#

foreach just checks whether what you pass to it has a GetEnumerator() method

heady iris
#

yeah

#

I don't think it even cares about implementing the interface

#

It's just a little โœจ language magic โœจ

rigid island
somber nacelle
#

i make that mistake like every single time i iterate over a transform lmao. every time i'm like "why isn't this working. . . oh right, i have to specify Transform"

rigid island
#

habit for me almost always writing var

heady iris
#

i usually just forget that i can do that and do a for loop

#

dodged!

#

then I write this and my game crashes

rigid island
#

lol

heady iris
#
while (transform.childCount > 0)
  Destroy(transform.GetChild(0));
#

boing

inner yarrow
#

Does anyone know what this error is referring to? It doesn't seem to be doing anything, but it just started showing up and I can't figure out what's causing it. It pops up now every time that I save a script.

somber nacelle
#

it's just an editor error likely due to something happening in a window that uses the graph editor like the shader graph or animator. you can ignore it as it won't affect the game

heady iris
#

I'd just give the editor a restart.

inner yarrow
#

ok sounds good

dapper rose
#

Hey has anyone found a good solution for intellisense of some kind for writing shaders in visual studio?

#

or is there a way to use both VScode and VS with unity? (so I can open shader files in VScode and cs files in VS)

rigid island
#

I also open my shader code in VSCode, for some reason VS corrupts them for me

#

there might be an extension for some type of syntax helper

dapper rose
#

yeah i only found extensions for older VS versions

#

i like 2022

#

how do u open in VScode?

#

from editor or from explrer?

rigid island
#

the only workaround i know ๐Ÿ˜ญ

dapper rose
#

thank you lol. do u have any extensions to help with intellisense in VScode?

rigid island
#

I dont write the code sorry lol that stuff I paste from the net

#

I usually have shadergraph for my own stuff

dapper rose
#

also does unity still recompile automatically on save If I edit in VScode?

latent latch
#

honestly it doesnt help that much

#

a lot of hlsl stuff has a bunch of unity functions and macros

rigid island
#

oh there ya go

#

thats why i use shadergraph xD