#archived-code-general

1 messages · Page 53 of 1

long totem
#

It should save the image to ImagePath in D disk

rigid island
#

that's not helpful. We understand that part

#

but do you see logs, etc.

#

be more specific and let's not play 20 questions here

long totem
#

there is no error in logs

thin aurora
swift aspen
fluid lily
#

Okay question. Is there anyway to get a projected position for a PlayerCharacter? Like I could do the math, but I am hoping there might be something built in for physics. Like what the position will be in a fixedUpdate later then the current one?

#

I am wanting this so I can have the camera/character graphics still be moving every frame, while the physics collider is between calls.

#

As the graphics/the camera renders at 120fps currently.

#

and physics is 40

#

Or possibly have physics update at 120fps for only the player character object?

main shuttle
# fluid lily Okay question. Is there anyway to get a projected position for a PlayerCharacter...

Kind of depends on your PlayerCharacter.

Extrapolation will predict the position of the rigidbody based on the current velocity.
https://docs.unity3d.com/ScriptReference/RigidbodyInterpolation.Extrapolate.html
There are a whole bunch of extrapolate or interpolate functions, you could study those if they fix your issue.
But afaik the basic extrapolate can't predict far into the future, but its probably a good starting point.

fluid lily
#

Ah nice. Yeah I don't need more than an an update or two, so that might do the trick

steep prism
#

I'm trying to use the GL system to draw lines but can't seem to get GL.Multmatrix method to work. The lines won't leave the default world rotation/position.

Right now my code is as follows: (abreviated)

//class GLLines
void drawLine(Color color, Matrix4x4 matrix,Vector3 Start, Vector3 End)
{
GL.PushMatrix();
//GL.LoadIdentity(); //tried both with and without
GL.MultMatrix(matrix);
GL.Begin(GL.LINES);

GL.Color(color);
GL.Vertex(Start);
GL.Vertex(End);

GL.End();
GL.PopMatrix();
}
void Update()
{
  GLLines.drawLine(Color.red, transform.localToWorldMatrix,Vector3.zero, new Vector3(512,256,0));
}

what am I doing wrong here?

long totem
#

Does that mean there is something wrong with my codes or VS?

crude mortar
#

you can use Camera.current if you want it to also work in the scene view

#

but you will want to call the method in OnDrawGizmos also

#

you are recreating the behaviour of Gizmos.DrawLine though, just so you know

thin aurora
#

Which is weird

steep prism
crude mortar
#

what is your new code?

steep prism
# crude mortar what is your new code?
void Update()
{
  GLLines.drawLine(Color.red, transform.localToWorldMatrix * Camera.current.worldToCameraMatrix,Vector3.zero, new Vector3(512,256,0));
}

The other code has not changed

crude mortar
#

and I think you can use OnPostRender() if your script is attached to a camera

steep prism
#

Uncommenting load identity doesn't change the result :(

steep prism
crude mortar
#

you never said you were on URP, but regardless I have no idea

#
        [UsedImplicitly]
        private void OnPostRender()
        {
            var matrix = m_lineParent.localToWorldMatrix * m_camera.worldToCameraMatrix;
            DrawLine(Color.red, matrix, Vector3.zero, Vector3.up, m_material);
        }
        
        private static void DrawLine(in Color color, in Matrix4x4 matrix, in Vector3 start, in Vector3 end, Material material)
        {
            material.SetPass(0);
            GL.PushMatrix();
            GL.LoadIdentity();
            GL.MultMatrix(matrix);
            GL.Begin(GL.LINES);

            GL.Color(color);
            GL.Vertex(start);
            GL.Vertex(end);

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

this works fine for me though (I am on standard pipeline)

#

the math should at least work in OnDrawGizmos though

#

then you could figure out how to make it work in the build

steep prism
#

that doesn't work on my end, at this point I'm stumped as to what it could be that causes it to not work. Thanks for help though, really appreciate it

crude mortar
#

weird, I blame some URP magic, not sure

#

unfortunately don't have a URP project for testing

#

yeah, seems like there is URP weirdness interfering, you might have to experiment a bit

#

the math is fine though, it's just a matter of where the code gets ran

steep prism
#

damn, alright. I'll try some things out and see if I can get it to work.

#

thanks!

golden vessel
#

Hey, I'm trying to stop a coroutine before starting again, but somehow the coroutine I stopped still runs, and interferes with the next one.

          combatEffect.currentBubbleCoroutine = StartCoroutine(combatEffect.CombatDialogue(buckAI.dialogueBuck[5]));```
Any idea what could be the problem pls?
plucky inlet
golden vessel
plucky inlet
golden vessel
#
    {
        List<(int, bool)> sentenceCut = CutSentence(text);
        bool ponctuation = false;
        bubbleObject.SetActive(true);
        bubbleText.text = text;
        bubbleText.color = new Color(0, 0, 0, 1);
        bubbleRend.color = new Color(1, 1, 1, 1);
        SetVoices(sentenceCut);

        int letterCountToNextSound = 0;
        bubbleText.text = "";
        foreach (char letter in text)
        {
            if (letter == ' ')
            {
                bubbleText.text += letter;
                yield return new WaitForSeconds(0.025f);
                continue;
            }

            if (letter == ',' || letter == '.' || letter == '?' || letter == '!')
            {
                ponctuation = true;
                bubbleText.text += letter;
                yield return new WaitForSeconds(0.025f);
                continue;
            }
            else if (ponctuation)
            {
                yield return new WaitForSeconds(0.25f);
                letterCountToNextSound = 0;
                ponctuation = false;
            }

            if (letterCountToNextSound == 0)
            {
                PlayNextSound();
                letterCountToNextSound = 4;
            }

            letterCountToNextSound -= 1;
            bubbleText.text += letter;
            yield return new WaitForSeconds(0.025f);
        }
        yield return new WaitForSeconds(3f);
        StartCoroutine(FadeBubble());
    }```
plucky inlet
#

!cs

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
plucky inlet
#

ah so your fadebubble is the one that is still running, right?

golden vessel
#

Basically it makes a bubble pop and fill it with text, than it makes it fade. But I guess there's a timing where the FadeBubble is running while the other one has stopped

#

Makes a lot of sense, I didn't think about that thanks a lot

plucky inlet
#

you are welcome 🙂

worldly zealot
#

I'm trying to set the simulation time for HDRP Water Surface so I can sync it in multiplayer but I don't see anything for that...

golden vessel
plucky inlet
#

Maybe for something like Sea of thieves to have the same waves going on

worldly zealot
#

if not synced, one might see a big wave but host sees nothing and it gets weird

plucky inlet
#

Did you check the shader and its values? Like the code version of the shader to see what modified it actually makes available?

plucky inlet
#

right click you rmaterial of your water and edit shader or script or something should appear

#

Let me check

golden vessel
#

Well, for a case like this I thought you'd base the shader on the physics

plucky inlet
golden vessel
#

But yeah I'm not knowledgeable about multiplayer to say I'm confident about it

plucky inlet
worldly zealot
plucky inlet
worldly zealot
#

seems like a new thing

plucky inlet
#

Ohhh, its a totally unique component. welp, can you right click edit script?

worldly zealot
#

yes i did check the script
there seems to be a section for simulation time which is private...

plucky inlet
#

But maybe you can overwrite the full renderingparameters?

#

Like you have to do with particlesystem emission modules, maybe this is also some kind of module

worldly zealot
plucky inlet
# worldly zealot there is nothing for that

Well it is quite new, gonna look at that myself in the next days. I would just tinker and test around with the scripts and see if I can overwrite anything or create from scratch in a script

edgy sage
#

Do you think there's something wrong with this code?

var go = new GameObject("_Guardian")
{
    transform =
    {
        position = transform.position
    }
};

var constraint = go.AddComponent(typeof(PositionConstraint)) as PositionConstraint;
if (constraint != null)
{
    var source = new ConstraintSource
    {
        sourceTransform = transform
    };
    constraint.AddSource(source);
    constraint.constraintActive = true;
}

It creates a GameObject called "_Guardian" and adds PositionConstraint component to it which has another gameobject (transform) as source transform. For some reason this _Guardian gameobject does not follow sourceTransform even though when I do exactly the same setup in the Unity editor it works.

leaden ice
#

You should just use the generic form of AddComponent

#

Did you mean to make the object the script is attached to be the constraint target?

crude mortar
#

also not sure why you are checking for a null constraint when you just created it

leaden ice
#

Probably because of the as cast

#

Which is a side effect of the whole not using the generic form of AddComponent thing

edgy sage
#

Generic form?

crude mortar
#

go.AddComponent<PositionConstraint>();

leaden ice
#

You should probably set the weight of the constraint source too?

edgy sage
#

It is 1 by default and in the inspector everything looks like when done manually

#

I will try with generic approach if that makes a difference

leaden ice
edgy sage
#

Maybe this constraint is somehow broken in Unity 2022.2.x which I'm using... no luck

leaden ice
#

Show the inspector of your object

#

After creation

#

I really think your field initializer for the Transform is fucked though

edgy sage
#

Transform is the yellow highlighted one

leaden ice
#

Isn't that wrong?

#

Also the source weight is 0

#

That's also wrong

edgy sage
#

Actually that might be the reason, source weight.. I thought it was source index

#

But axis is set like that also when it's working when done manually

#

Yep, working now that I set source weight

#

Thank you, I missed that one when trying to figure out what is the difference between manual setup and scripted 🙂

#

Following the player nicely now.

proven path
#

What would happen if I try to deserialize a json file, containing a deriving class as their base class. Can I cast it into the deriving class afterwards, or will it just throw an error?

leaden ice
#

In general you would need to store type information with the data

#

Newtonsoft JSON has support for this

proven path
somber nacelle
#

jsonutility is pretty barebones tbh. i'm not even certain it supports polymorphic deserialization. you'd probably have a better time switching to newtonsoft

plucky inlet
thin aurora
#

Unity has a Newtonsoft package which is a million times better

#

The limitations of JSONUtility is so laughably bad that I am surprised Unity even still has it available as an actual feature

proven path
#

I will give Newtonsoft a try then; thanks guys!

unreal temple
#

How can I serialize an SO into the UserSettings/ folder?

leaden ice
#

The novelty of JSONUtility is that it uses Unity's standard serialization mechanism. It's also faster than Newtonsoft

stiff tide
#

I have a frustrating bug that googling doesn't seem to find anything.

I'm loading images (sprites) from a 'Resources' folder using, 'Resources.Load<Sprite>'
This function/method is called once, when the card is created. It sets the image, and all is good. At a later time, it's called once, setting the image/sprite of another object. Which works. It finds it's own image, and it finds the other object's image. But... it then changes what it's own image is. It never actually does it, it only runs this search again. Which gets applied to both objects for whatever reason. It's retroactively changing the variable of the first one.

In short,
Image1 = Image1.png
Image2 = Image2.png
Now Image1 and 2 both equal 2.

public Sprite SearchDownloadCardImage(string cardName)
    {
        // In the future, this will actually search for and download images. Right now it can only pull files that are already downloaded.
        try
        {
            Sprite result = Resources.Load<Sprite>("Card Images/" + cardName);
            if (result != null) return result;
        }
        catch
        {
            Debug.Log("Failed to find '" + cardName + "' in the Resources file.");
        }
        return DefaultImage;
    }```
With a bunch of debugging, I'm 99% sure it's only this line of code breaking things.
orchid bane
#

Anyone knows where to find navigation algorithms for such a node map?

stiff tide
thin aurora
thin aurora
#

Because as soon as my shit game is actually going to function like it's supposed to it will encounter a lot of features that will chew on that performance

#

Now take a guess how JSONUtility relates to this

twin stag
#

Unity is throwing an error up in a class I made when I try to make a public image variable saying "the type or namespace 'image' can't be found" but I have got using UnityEngine.UI; at the top. It's a 2nd class inside the same file as another class. A tutorial done in 2020 Unity shows this working but it's not in 20201 LTS Unity.

somber nacelle
#

make sure you're spelling it correctly

twin stag
#

It's a PlayerNeeds class file with a 2nd class of "public class Need"

#

public image uiBar;

proven path
#

Make sure that image is uppercase.

somber nacelle
#

make sure that your !IDE is configured so you don't make spelling mistakes like that

twin stag
#

using UnityEngine.UI; is at the top of the file

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.

tepid river
twin stag
tepid river
#

so thats not the cause. the DefaultImage could become a shared object
all in all, i smell that this method is probably not the cause

somber nacelle
stiff tide
# tepid river so thats not the cause. the DefaultImage could become a shared object all in all...

Default image is never used. This method is the only thing that sets the card's image, and sets the zoomed in one, when it's alone (in play). When the one line that calls this method is commented out, everything is fine. (It just doesn't display anything when the card is in play. If I were to skip calling this method during the in play exception, and skipped right to giving it the Default image, everything is good.

This method is retroactively changing what it found the first time.

tepid river
#

sprite and cardname are local to the methods scope. it cant change them that way. can you show the surrounding code?

stiff tide
#

It should make two distinct spite variables, but that's not what happens for some reason

#

I can... but I just left for work. So I can't do it for a few hours sadly. Ttyl

high violet
#

any idea to implement AI that you pointed
I have done the previous steps just creating the AI is left which seems to be important 😅

orchid bane
#

How do I give such red and green outlines dynamically?

leaden ice
thick socket
thin aurora
somber nacelle
#

it can just not as the root object

thin aurora
#

Yes that's what I mean

lost wave
#

when the game moves from lvl 2 to 3, the transition animator controller gets removed from the inspector. It works fine from lvl 1 to lvl 2.

thick socket
lost wave
thick socket
#

you didn't share the errors

lost wave
#

MissingReferenceException: The variable transition of LevelLoader doesn't exist anymore.
You probably need to reassign the transition variable of the 'LevelLoader' script in the inspector.
UnityEngine.Animator.SetTrigger (System.String name) (at <b492836710f1493ca0190fe9374a37da>:0)
LevelLoader+<LoadLevel>d__5.MoveNext () (at Assets/Scripts/LevelLoader.cs:27)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <db7f68c084e842d98504c53b2b4dd3db>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
LevelLoader:LoadNextLevel() (at Assets/Scripts/LevelLoader.cs:19)
LevelLoader:Update() (at Assets/Scripts/LevelLoader.cs:37)

maiden breach
#

Where are you setting that transition variable?

#

Find All References

#

look for ones that write

orchid bane
#

How do I get the prefab of a prefab instance?

maiden breach
lost wave
orchid bane
thin aurora
plucky inlet
plucky inlet
maiden breach
orchid bane
lost wave
plucky inlet
plucky inlet
plucky inlet
plucky inlet
# orchid bane Can you rephrase?

If you have a list, you can use IndexOf(yourPrefabSource) to pass in a value to your prefabInstance. So you set it when instantiating.

orchid bane
#

I don't understand what "to pass in a value to your prefabInstance" means.
As I see it, I need first to get the prefab of my prefab instance

plucky inlet
lost wave
maiden breach
plucky inlet
orchid bane
plucky inlet
#

do you have some code to look at? where you instantiate and where you need the index?

orchid bane
plucky inlet
orchid bane
#

Sorry

lost wave
plucky inlet
# orchid bane Sorry

So what part of the code is your issue now? The currentIndex value? Is it wrong, do you get any error?

lost wave
orchid bane
plucky inlet
vestal geode
#

Are switch expressions just lambda expressions for a switch statement, or something more?

plucky inlet
#

Oh well, looking at the microsoft docs, they might be a little different as you can convert values to a desired target value on different types

plucky inlet
plucky inlet
unreal temple
#

Is it possible to modify/preview a material property block in the editor?

quaint rock
unreal temple
#

I want the optimisation without losing the nice material editor.

unreal temple
#

Yeah, I can do that haha, going to be annoying in prefabs though.

quaint rock
#

though generally its not used for static stuff

#

but per instance changes

unreal temple
#

Well yeah.

#

But that doesn't mean you don't want an artist to pick the colors and preview them

#

Or is there no difference between property blocks and authored materials for performance?

quaint rock
#

but yeah you could easily hook it up in OnValidate or something

#

so it changes during edit time

unreal temple
late lion
#

SRP Batcher prefers material instances

unreal temple
#

Is that something that's on by default in URP?

late lion
#

I imagine so. I think it's a hidden setting.

unreal temple
#

Okay, so we're probably using it. In that case it will be easier to just create materials.

#

Seems I have wasted some time here.

late lion
#

Yeah, I said "prefers", but MPB actually breaks batching when using SRP Batcher. It just doesn't know what to do with it so it doesn't combine it with anything.

unreal temple
#

That's good lol

#

Certainly good to know, thanks

late lion
#

It can still fallback on GPU instancing if the material supports it.

unreal temple
#

I'm not even concerned about performance, I'm just mildly worried about artists authoring a whoel bunch of the wrong kind of asset.

late lion
#

Material variants in 2022 will help with this.

unreal temple
#

Oh, we're about to upgrade to 2022

#

Ah, just like a prefab variant

#

Nice.

late lion
#

Prefab Variants and Material Variants have much the same functionality, ... There are two key differences between them:

You can reparent a Material Variant.
You can lock Material Variant Properties.

unreal temple
#

Beautiful

golden vessel
#

Hey, is the Time.time accurate for audio? I'm pretty sure music still runs in most game when having a freeze, so I suppose it's not.
I'm trying to count the time so that I can switch music on a beat

lost wave
#

Just answer the last question 🙂 You set

hard sparrow
#

I've got text with a content size fitter inside a layout group (so the textbox resizes automatically). But it doesn't correctly update the first time text is posted. I'm even doing THIS

golden vessel
deep fable
#

Any idea on how I could procedurally generate a desert? (like the one in the photo, source: https://blenderartists.org/t/procedural-desert/1321823)

I was thinking about using cellular noise to generate the dunes, and then use a "zoomed out" perlin noise to offset the dune height (and avoid that every dune has the same height), but dunes don't seem to have straight edges like cellular noise does

hard sparrow
# hard sparrow

This is (I thought) forcing the text to update and the layout group to update... but it still doesn't do anything initially

plucky inlet
golden vessel
#

How many of these timelines are they btw? Cos I can count at least the usual one, the physics one, and the audio one

deep fable
#

Maybe I could something like a 1d perlin noise to offset the dune

#

Thanks!

hard sparrow
#

dunes often do have sharp edges though

deep fable
# hard sparrow

But that's a feature that also cellular noise has (don't mind the 3d sphere)

#

Maybe it's not that good the cellular noise.. I'll see

plucky inlet
# hard sparrow

you could just have a range decreasing for the x values too while that range gets offset depending on the y value

late lion
plucky inlet
#

like decrease the range to get sharper edges AND shift that range to get those steep cliffs

late lion
hard sparrow
# hard sparrow

So should this be having the effect I want it to have? actionDescription being the text itself and actionAttributeLayoutGroup being the vertical layout group of the parent object which the text is childed too.

golden vessel
#

Thanks, I'm pretty sure I'll just adapt the example of PlayScheduled on the unity docs, but I wanted to understand it beforehand

hard sparrow
#

Second time. (This is correct)

#

Is this a normal issue or

golden vessel
hard sparrow
plucky inlet
#

You might not rebuilding the correct parent

golden vessel
#

Maybe you change stuff before the rebuild? Idk I've had trouble with that as well and ended up doing it in editor rather than code

hard sparrow
golden vessel
plucky inlet
#

Maybe show your full code

hard sparrow
#

Does ForceMeshUpdate on the text do anything relevant?

plucky inlet
#

It updates the TMPro but not really playing into the UI recalculation at first I think

hard sparrow
#

I'll play around with it some more

golden vessel
#

I'll just put that link there, I followed the tutorial and it saved me a lot of troubles

plucky inlet
#

Do you reubild after the bunch or after every text?

golden vessel
#

Actually I didn't at first and ended up spending hours for it not to work aha

thick socket
#
NullReferenceException: Object reference not set to an instance of an object
OfferIcon.SetAmount (System.Int32 tmpamount) (at Assets/Scripts/UI/MainMenuScripts/Offers/OfferIcon.cs:28)
OfferIcon.Spawn (UnityEngine.UIElements.VisualElement tmp, OfferIconTrees offerIconTrees) (at Assets/Scripts/UI/MainMenuScripts/Offers/OfferIcon.cs:33)
Offer.Initialize (OfferData data, UnityEngine.UIElements.VisualTreeAsset tree, OfferTypes tmptype, OfferIconTrees offerIconTree) (at Assets/Scripts/UI/MainMenuScripts/Offers/Offer.cs:38)
ShopOffers.InitialAddOffers (OfferData item, OfferTypes tmpType, System.Int32 timeOffer) (at Assets/Scripts/UI/MainMenuScripts/Offers/ShopOffers.cs:88)
ShopOffers.InitialAdd () (at Assets/Scripts/UI/MainMenuScripts/Offers/ShopOffers.cs:48)
ShopOffers.Start () (at Assets/Scripts/UI/MainMenuScripts/Offers/ShopOffers.cs:25)
#

assuming you see somehting like this error

#

is there a fast way to get to the "top" aka jump to OfferIcon.cs:28

#

instead of jumping into ShopOffers.cs:25?

pearl swallow
#

https://pastebin.com/LuebWMR1

Still having an issue with being able to set the "plant" GameObject to be 10 below the current y value of a TunnelArray object, it moves to the spot, just not 10 below.

hard sparrow
golden vessel
pearl swallow
#

Like it should be subtracted by 10.

golden vessel
#

If the object is not root of the hierarchy, and one of its parents scale is not 1, the position will get affected by the scale

pearl swallow
#

Like say if it was put at 0,10,0, the code should just have it be 0,0,0.

#

I'm not sure I follow.

golden vessel
#

Say you have 2 objects, one parent and one child

#

If the parent scale is (1,1,1), and you code child.transform -= new Vector3(0,10,0), the transform will be the same, -10 on the y axis

#

If the parent scale is (2,2,2), the child transform will be the same, -20 on the y axis

#

If you want the child to be the same -10 on the y axis, you need to use transform.localPosition

#

Rather than transform.position

pearl swallow
#

I'll try that, thank you.

blissful flower
#

So I have a line like this

#

where Unit is a general Unit script. Recently I refactored some stuff so that now different units have their own unit classes that just inherit the general Unit

#

(so UnitMage : Unit, UnitWarrior : Unit, UnitGoblin : Unit)

leaden ice
#

I think that's a bad practice in Unity in general to use polymorphism that way 🤢

blissful flower
#

how do I get that component without knowing the actual name of the class?

leaden ice
#

GetComponent<Unit> will still work

#

They are all still Unit

blissful flower
#

Yep it does but when I try to get unit.skillArts[0] for example, I don't think that works anymore?

leaden ice
#

Why not?

#

is skillArts part of Unit?

#

Then it will work

blissful flower
#

yeah, so it should work? hmm

leaden ice
#

Better practice btw would be for those GameObjects to just have multiple components:
Unit AND Goblin
Unit AND Warrior

#

composition > inheritance for Unity

blissful flower
#

🤔

#

So hold on... could Goblin or Warrior in that case still inherit Unit or not?

leaden ice
#

It should not

#

that's the point I'm making

#

don't use inheritance like that

#

What happens if you want a GoblinWarrior

#

or a Goblin with a shield

#

Do you make GoblinWarriorWithShield: GoblinWithShield : Goblin : Unit ???

#

It's not a good model

#

the better model is you have a GameObject named GoblinWarriorWithShield that has multiple components attached:

  • Unit
  • GoblinAI
  • Shield
blissful flower
#

But in my case I have like 50 heroes/units that all share the basic rules for everything, like default movement, taking damage, having two skill buttons (one of which can be disabled) etc.

leaden ice
#

right

#

that's what the shared components like Unit are for

pearl swallow
#

Would the Start method override anything?

blissful flower
#

So what if I want to override something in Unit? Let's say that Warrior doesn't use default movement but a slower movement instead

#

and it has the Unit and Warrior components

#

what does the Warrior component do if it can't inherit the default movement even (to be overridden)?

leaden ice
#

or movement is handled in Warrior / Goblin, not in Unit

#

And can't "slow" just be handled by a public float speed; variable on one of the scripts?

#

You don't need inheritance to have a different speed value

blissful flower
#

No because the movements are tile-based and might be in different shapes, not a value

leaden ice
#

So you have:
TilebasedMovement
LMovement
etc. components

#

these should not be part of Unit

pearl swallow
# golden vessel If you want the child to be the same -10 on the y axis, you need to use transfor...
    //The "Tunnelling" section for the Plant. Plant burrows down, selects spot before coming up in later section.
    public void PlantTunnel()
    {
        plantIndex = Random.Range(0, 3);
        plantStatus = 1;

        transform.localPosition = tunnelArray[plantIndex].localPosition + new Vector3(0, -10, 0);

    }

    public void PlantUntunnel()
    {
        transform.localPosition = tunnelArray[plantIndex].transform.localPosition;
        plantStatus = 2;
    }

Was this what you meant when using transform.localPosition?

leaden ice
#

or maybe Unit just has a MovementStrategy enum field

#

etc..

#

I'm throwing things out there because I don't know how your game really works but, reaching for inheritance to solve every problem is a bad instinct in Unity.

blissful flower
#

Well the core issue is... my Unit script is like 3000+ lines long, and it's structured so that each different hero or unit has a "UnitID" which is just an integer.
Then we come to the "CheckMovement()" function for example that checks which tiles the hero is allowed to move to based on their movement rules, and inside it there is a massive if else chain (not even switch for christ's sake) that checks if unitID = 30, check these tiles: if unitId = 35, check these tiles:
etc.

pearl swallow
#

Post it in Pastebin

blissful flower
#

doesn't that sound horrifying? And that goes for everything

#

and I figured I'd make a base Unit class that has the defaults for everything, and then each unit has an inherited UnitWarrior for example that might override the default CheckMovement() in some unique way

leaden ice
#

What I disagree with is that those separate scripts should inherit from Unit

#

movement rules in particular can be one script or a separate script hierarchy (BaseMovement, GridMovement, whatever)

pearl swallow
#

I figured it out

leaden ice
#

things dealing with basic health/unit targetting can be another script (the Unit script)

pearl swallow
#
if(plantStatus==1 && plantStatus < 5)
        {
            transform.position = tunnelArray[plantIndex].position + new Vector3(0, -10, 0);
        }

My solution.

#

So, it didn't update it... but did?

#

I put this in the update method just in case and it fixed it.

#

Welp, I'm happy now.

#

Also… 3000+ lines…

#

Why

#

That… I get maybe having 100+ if it’s like a really heavy script and it needs to be all in one.

#

But 3000+?

blissful flower
#

Let's say I have a function that should check movement of ALL units currently on the field

#

it would need to call the CheckMovement() (or similar) of each different Movement component

#

How do I do that?

#

Or actually... should Unit have a reference to it's correct movement checking script

leaden ice
leaden ice
blissful flower
#

That would actually make a lot of sense I think. So for each different hero I will go and have Unit component which has a Movement script reference, and for units that don't use the DefaultMovement script (for example) I just set WarriorMovement there. Would this make sense? So then I could make all units check their movement and they will do it using the attached movement script

#

Is this a sensible solution or am I still gonna do something horrifying

leaden ice
#

yes something like that sounds sensible

#

I think for Movement in particular inheritance might make sense within that area

#

it would then be super easy for you to mix and match things

#

like a Goblin with a TileMovement and another Goblin that has JumpMovement (just making things up)

blissful flower
#

Thank you so much for the help. Actually awesome explanations and I feel I learned something from this

#

I'm in for some insane labor though because movement is only one of the many things Units have. So gonna have to split the current gigantic Unit script to tens of other scripts but oh well this is a hole I've dug myself into

sinful ginkgo
#

how can i use .FirstOrDefault() on a NetworkList or at least convert the NetworkList into a standart list?

haughty cairn
#

hello, i am struggling to wrap my head around this problem, I want this cleaver to slice the fish in half, but the user will have control over where to slice. How could I dynamically slice the mesh? I was thinking of duplicating the object and hiding part of it, but cant find a way to do that. Would really appreciate advice (or point me to the right channel)

golden vessel
night bloom
#

Is there a way to have 1 particle follow a path or game object. Example if i spawn a glowing knife that is supposed to chase a unit. Does that knife need to be a game object or can i do it with particles? the unit can run anywhere i just need the knife to chase it

swift falcon
#

why would you want it to be a particle instead of a game object?

night bloom
#

I have no preference. I just downloaded some cool effects and wanted to use them. they are all particle systems so i was wondering if that would work

swift falcon
#

just make a gameobject with the same texture and material and all that

#

and then look up on youtube how to make it follow another gameobject depending on if you want it to just go in a straight path or act like a missile or whatever

eager yacht
haughty cairn
# eager yacht could try using something like this <https://github.com/DavidArayan/ezy-slice> (...

oh! awesome! thanks! I also ended up finding this : https://www.youtube.com/watch?v=InpKZloVk0w which ill put in case anyone else has the same issue

🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle

💬 ProBuilder has an awesome feature that is surprisingly hidden.
You can make various Boolean operations on your Meshes allowing you to easily Slice, Cut, B...

▶ Play video
swift falcon
#

does anyone know how i'd go about combining multiple images into one procedurally in script, but not just overlayed on top of each other or anything, but where each image takes up a portion of the image?
so if it's 3 images combined into one, each one takes up a third of the image

maiden breach
#

for example, if you simply must have them combined into one image, it's certainly possible. But if you're just trying to show multiple images in the ui as one image, you could use Masks and it would be a lot easier and flexible

swift falcon
#

oh i think having them be multiple images but show as one would work just fine
how would i do that using masks?

maiden breach
#

Set them up in whatever arrangment you want and each mask gets a child with the image you want to show in their section

pearl swallow
#

It triggered it, but didn’t update fully

#

Idk

swift falcon
#

imagine a pie chart kinda deal

maiden breach
#

you can do that

swift falcon
#

oh i see what you're saying

#

i'm not sure how to get them in the arrangement that i want though

#

splitting it up like that i mean

maiden breach
#

I believe unity provides a circle sprite that you can radially fill

swift falcon
#

bet i'll check that out ty

maiden breach
#

@swift falcon no code necessary

#

doing it procedurally based on a variable number of images would be a different story

swift falcon
#

i would want to do it procedurally but i don't think it'd be too hard

icy sundial
#

is it possible for something to have a SortingOrder only within its context?
i.e. ive got a panel with sorted stuff and I put this panel on top of itself, i dont want the things from the behind panel to show through

icy sundial
#

sorry

quasi stirrup
#

Does anyone know any good Unity beginner guides for people who already know how to code?

#

I'm looking for something like a series of tutorials on creating an example project that doesn't also teach you basic coding..

#

There's a lot to unity that isn't just API stuff

maiden breach
#

Not a dumb question. Unity development is conceptually different than traditional application development. Case in point - frames.

#

That said, Unity Learn is a good place to start @quasi stirrup

#

where did he say he doesn't know c#?

quasi stirrup
#

I know C#..

crude mortar
#

and since when is C# somehow unique from all other languages

quasi stirrup
#

and even if I didn't Java is extremely similar

crude mortar
#

most of them are quite similar

#

thats why they are asking for beginner guides

#

to Unity

quasi stirrup
#

I'm trying to find something for unity that doesn't try to teach me what a variable is for the 50th time, not exactly groundbreaking

crude mortar
#

imagine this scenario: you are an experienced 3D modeler, but you switch from Blender to Maya... You don't need to relearn basic topology rules and general good practices, you just need to learn the new tool

#

so naturally you would ask for beginner maya tutorials that already assume you know things about modeling

#

instead of starting from complete scratch

wintry crescent
#

Hi, I'm trying to make an object swing like on a rope

        Transform attachedRigidBodyTransform = _attachedRigidBody.transform;
        Vector3 offsetToAttachedRigidbody = attachedRigidBodyTransform.position - transform.position;
        Vector3 directionToAttachedRigidbody = offsetToAttachedRigidbody.normalized;
        // Set the distance to the rope length.
        if (offsetToAttachedRigidbody.magnitude > _ropeLength)
        {
            Vector3 newPosition = transform.position + directionToAttachedRigidbody * _ropeLength;
            _attachedRigidBody.transform.position = newPosition;
        }
        // allow swinging of the object, 
        // by adding a force in the opposite direction of the offset.
        float forceMultiplier = Vector3.Dot(Physics.gravity.normalized, directionToAttachedRigidbody);
        _attachedRigidBody.AddForce(-directionToAttachedRigidbody * Physics.gravity.magnitude * forceMultiplier, ForceMode.Acceleration);

this is my rope code, the rope object is located at the anchor
the attached object swings, but it stops at the midpoint instead of swinging the other way
the rigidbody has no non-angular drag on it, and there is no other things affecting the swinging object
Why doesn't it swing properly?

wintry crescent
quasi stirrup
#

I'm not asking to skip learning API I'm looking for a tutorial that doesn't make me re-learn C#

solemn raven
#

hi ,
I wanna run function on a button is Pushdown/pressed even not on click
basically, I want to manually activate some animation/sound on press

#

you may say I want to create a custom PressedColor effect for the button

leaden ice
#

and add a PointerDown event

#

(you can even delete the Button component if you don't care about normal button stuff)

solemn raven
#

Thanks ❤️

wintry crescent
#

I'm not sure where to even begin looking for the bug

leaden ice
wintry crescent
wintry crescent
leaden ice
wintry crescent
leaden ice
wintry crescent
# leaden ice I didn't say anything about visualizations

I mean - many hinge joints would require me to make a string of objects between the anchor and the attached object, correct?
I do not need that, even though it would maybe be more accurate, I just wanted to make a simple rope swinging with a bit of math
Or is using hinge joints the easiest way?

leaden ice
polar marten
wintry crescent
wintry crescent
polar marten
#

it's complicated

#

there's no "just" and rolling your own

#

obi rope is pretty mature

wintry crescent
polar marten
#

i understand yeah

#

i don't mean to discourage you

silver void
#

How do you folks handle chaining transient modifiers together? An example would be MovementSpeed which can be modified by powerups, the "sprint" button, equipment the player is wearing, etc. Since these things modifiers are transient (I expect them to change often during the course of the game) and numerous, I'm trying to design an easy-to-maintain system which can reliably apply modifiers.

The system I've prototyped is a list of delegates related to the attribute being modified. Each delegate represents a modifier and it is identified by an enumeration. A list of the active modifiers, identified by their enumerations, iterated through to determine the current value whenever a modifier is added/removed. For example, one delegate would multiply the current value by 2, another would add +1 to the base value, and a third would divide the current value by 2. This turns the determination of current state into something of a functional mathematical problem instead of embedding it elsewhere in the game logic, and it also provides a mechanism for checking active states for problems that are simple enough that they don't require a full-blown FSM with transitions and what not. I do see a few disadvantages. however, and I'm wondering what other folks do.

Thanks for any response!

leaden ice
#

then you Add/Remove modifiers as needed

#

you can make a float cachedValue too, and only calculate once when adding/removing a modifier

silver void
hollow junco
#

Is there any way to have 2 functions with the same name and same arguments types and order but implemet 2 diffrent logic on the same class ?

late lion
maiden breach
leaden ice
#

If you use sorted list then when you remove you have to do so by the priority as the key? That's funky

#

anyway this implementation is commutative so order doesn't matter

rain minnow
hollow junco
rain minnow
#

the real question is what does each — method — implementation do?

maiden breach
rain minnow
#

@hollow junco if they do different things, they should have two different names. the parameters can be the same if you want . . .

hollow junco
#

Because they implement a function with that specific name@in the base interface. But in the class this function behaves diffrently depending on some circumstances

leaden ice
rain minnow
hollow junco
leaden ice
hollow junco
leaden ice
#

no magic.

rain minnow
#

i was just thinking this . . .

public void SomeMethod(MyType myParam)
{
    if (circumstance)
    {
        this.SomeMethod(myParam);
        return;
    }

    // Non-circumstantial stuff ...
}
late lion
leaden ice
#

naturally you'd tailor the implementation to your actual requirements

#

Shouldn't you be able to get a modifier that adds a +1 after all other modifiers?
Maybe your game needs this, maybe it doesn't.

rigid island
#

still considered cross-posting to do so

velvet trail
#

Hello, I´m currently having an issue with raycast and colliders. My player´s colliders are so big that they´re in the way of the raycast. And I wanted to ask if there´s a way to make that raycast ignore the players Collider ? Thanks

ocean quail
#

Okie dokie

late lion
rigid island
velvet trail
#

so it should look like this ?

granite glen
#

Does anyone know how to check if an AssetBundle is cached before attempting to download it?

rigid island
#

you want player excluded it shouldn't be part of LayerMask for the ray

#

you want Every other layer but the Player layer

rigid island
#

if(Physics.Raycast(... , allOtherLayer)

velvet trail
#

oh riight. Got it 😄 I thought that the layer should be player only. I changed it in the inspector and it´s working now 😄

#

Thank you !

rigid island
#

you can only put player inside and do playerLayer = ~playerLayer

#

playerLayer = ~playerLayer
if(Physics.Raycast(... , playerLayer)

velvet trail
#

Ok, I´ll probably use just that one layer. But Thank you.

languid saddle
crystal holly
#

hey guys, i'm trying to use JsonUtility.FromJson to parse a json string containing mesh data.
my json looks like this but i'm getting nonsensical values after parsing. could it be because of the many decimal places?

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

tepid river
crystal holly
#

that's exactly what i thought 😄

leaden ice
#

actually I don't think JsonUtility takes regions etc into account 🤔

crystal holly
languid saddle
#

It streches

rigid island
languid saddle
#

Let me explain with a draw, give me 1 min

crystal holly
leaden ice
languid saddle
rigid island
languid saddle
#

Sorry for my explanation, yes

crystal holly
rigid island
#

when you resize an object you're also stretching the UVs

#

hence the stretch look

languid saddle
#

So i cant do it in player?

rigid island
languid saddle
#

ok, so what sould i search to get a tutorial?

maiden breach
rigid island
#

or you can try ProBuilder, i believe it has options where you can keep the UV stretch-independent

languid saddle
#

Ok, thank u :)

crystal holly
zinc parrot
#

With the RayTracingAcclerationStructures, is there a way to have a TLAS or top level acceleration structure?

crystal holly
swift falcon
#

I have attached three instances of a basic custom sound randomizer component to a weapon of mine. I have a fourth script that does everything else whenever I fire the weapon.

How would I get the weapon to play a sound from each of those sound randomizer components upon firing the weapon?

rain minnow
swift falcon
#

Does GetComponent fetch all components under the listed name?

rain minnow
#

well, you shouldn't have more than one of the same component on a GameObject. they should be placed on children . . .

swift falcon
#

Oh.

#

Ok.

#

In that case that'd change things... 🤔

rain minnow
swift falcon
#

I'll come back later.

rain minnow
#

if it doesn't matter which custom sound component plays first, then it's nota problem . . .

rain minnow
swift falcon
#

🤔

river wigeon
#

Could someone help me figure out why the UI looks fine in the editor but not in the build?

#

The 2 players tags should be next to each other like the editor

rain minnow
polar marten
river wigeon
#

This is what my UI looks like

river wigeon
#

yeah it looks weird when I change the aspect ratios

#

found the option

#

child force expand

#

unticking height has fixed 👍

swift falcon
#

i'm accessing my data class on my Manager singleton, which works fine except for when i open the gameobject in the inspector, where it lags a lot due to how much data there is/ how many fields there are, what are some solutions to this?

swift falcon
rigid island
#

anything above 300 lines, already doing too much in one class

#

not sure if it relates to your issue though

dim whale
rigid island
dim whale
dim whale
rigid island
#

Yeah mainly, just makes it easier to debug as well

stiff tide
# tepid river sprite and cardname are local to the methods scope. it cant change them that way...

This is the function/method I'm having a problem with:

public Sprite SearchDownloadCardImage(string cardName)
    {
        try
        {
            Sprite result = Resources.Load<Sprite>("Card Images/" + cardName);
            if (result != null) return result;
        }
        catch
        {
            Debug.Log("Failed to find '" + cardName + "' in the Resources file.");
        }
        return DefaultImage;
    }

When the card is created, it calls this method.

public void FlipOrShow(string flipDirection)
    {
        string cardName = cardNamePair;
        if (isSecondPairImage) cardName = cardNameTop;
        Sprite CardFront = SearchDownloadCardImage(cardName);

        Sprite currentSprite = gameObject.GetComponent<Image>().sprite;

        if (flipDirection == "Front")
        {
            gameObject.GetComponent<Image>().sprite = CardFront;
        }
        else if (flipDirection == "Back")
        {
            gameObject.GetComponent<Image>().sprite = CardBack;
        }

And when you hover over the card, it's meant to display it's own image onto a larger card. (A hover and zoom mechanic). It's also supposed to display it's parent or child.

public void OnMouseHoverEnter()
    {
        ZoomedInSprite = gameObject.GetComponent<Image>();
        ZoomCardTop.GetComponent<Image>().sprite = ZoomedInSprite.sprite;
        // [It searches for it's pair here.]
        if (cardPair != null)
        {
            ZoomedInSprite = cardPair.GetComponent<Image>();
            ZoomCardPair.GetComponent<Image>().sprite = ZoomedInSprite.sprite;
        }
        else
        {
Debug.Log("Found Neither!");
            string cardName = cardNameTop;
            if (isSecondPairImage) cardName = cardNamePair;
            ZoomedInSprite.sprite = SearchDownloadCardImage(cardName);
            ZoomCardPair.GetComponent<Image>().sprite = ZoomedInSprite.sprite;
        }
rain minnow
stiff tide
dim whale
# swift falcon i'm accessing my data class on my Manager singleton, which works fine except for...

If you right-click the script component bar, and select 'Properties', a separate window will pop up for only that component. (Perhaps this lags less).
A more direct approach is to expose less fields at the same time.
NaughtyAttributes has an attribute for Foldout groups (https://assetstore.unity.com/packages/tools/utilities/naughtyattributes-129996)

public class NaughtyComponent : MonoBehaviour
{
    [Foldout("Integers")]
    public int firstInt;
    [Foldout("Integers")]
    public int secondInt;
}

https://raw.githubusercontent.com/dbrizov/NaughtyAttributes/master/Assets/NaughtyAttributes/Documentation~/Foldout_Inspector.gif

stiff tide
#

Actually, you were right. As a test, I just replaced the method call with a default image. The default image shows... and also replaces the card's original image.

I changed only one part of one line:

public void OnMouseHoverEnter()
    {
        ZoomedInSprite = gameObject.GetComponent<Image>();
        ZoomCardTop.GetComponent<Image>().sprite = ZoomedInSprite.sprite;
        // [It searches for it's pair here.]
        if (cardPair != null)
        {
            ZoomedInSprite = cardPair.GetComponent<Image>();
            ZoomCardPair.GetComponent<Image>().sprite = ZoomedInSprite.sprite;
        }
        else
        {
Debug.Log("Found Neither!");
            string cardName = cardNameTop;
            if (isSecondPairImage) cardName = cardNamePair;
            ZoomedInSprite.sprite = DefaultImage; // This is the line I changed.
            ZoomCardPair.GetComponent<Image>().sprite = ZoomedInSprite.sprite;
        }
swift falcon
# rigid island don't make monolith classes

so i should split my data class into a bunch of different classes? i'm not sure how i'd serialize and deserialize that, and it'd be annoying needing to reference different data classes for every little thing

rigid island
swift falcon
#

oh yeah no i have several managers, but just one data class

rigid island
#

I send events to a singleton EventManager so i dont couple anything

swift falcon
#

since writing that i tried changing to just a singleton Data class not on the Manager class, which i guess reduced the lag since i can't even open it in the editor now lol

swift falcon
swift falcon
dim whale
swift falcon
#

2021.3.5f1
i already moved it to its separate class and changed every reference so i can't really screenshot

#

i can send a save file though which would give a decent idea

rain minnow
#

10, 100, 200, etc.?

swift falcon
#

save file is 70k lines lol

rain minnow
#

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

swift falcon
#

that's not code it's a save file

dusk apex
#

Ah, alright.

#

70k lines or file size?

swift falcon
#

lines

#

file size is 892kb on a fresh save

#

the biggest perpetrator is the cell data which saves the 20x20 grid and the contents of the cells

rain minnow
swift falcon
#

without it it'd be like less than 1-2k lines

#

it's over the pastebin file size limit

rain minnow
#

wow, never seen that before . . .

swift falcon
#

i'll paste it with the all cell data removed except for one

dusk apex
#

See a lot of redundant data (blank fields) being recorded

swift falcon
#

which specifically?

dusk apex
#

Practically the same data for many objects:

#

Data that doesn't need saving or that are always default should just not be serialized?

swift falcon
#

1: idk how to not serialize it
2: if i don't serialize it then i'll need to check for if it's not there and create it when i do want to use those stats

dusk apex
#

Unless this sample's a coincidence..

swift falcon
#

nope

#

every object that can hold the seed class has its seed serialized even if it's null

#

lol

#

it works fine in saving and loading but now you might see why the inspector was lagging lol

rain minnow
#

do you need to see the data class from the inspector? makes sense to just check the save file . . .

swift falcon
#

it's useful for debugging but no i don't need to, that's why i moved it to its own class

dim whale
dusk apex
#

A fold out group could reduce clutter - not sure if it'll reduce inspector delay.

dim whale
#

Linked him NaughtyAttributes for that earlier

swift falcon
#

oh i meant i moved it to its own non monobehaviour class since i can't deserialize to a monobehaviour

rain minnow
#

i thought it was already a c# class, not a MonoBehaviour . . .

swift falcon
#

yeah but earlier it was on the Manager monobehaviour

#

now it's not on one so i can't see it in the inspector

#

it's fine like this tho not a big deal

lyric wadi
#

that data would gzip down probably 98% since it has so much repeated data

swift falcon
#

i'm not sure what gzip is but yeah compressing with 7-zip cuts the size by 16 times

dusk apex
#

That's what I was getting at. It seems a lot of fields were saved for no particular reason.

dim whale
#

GZipStream

dusk apex
#

Lot's of empty strings and zeros

lyric wadi
swift falcon
#

i could not save the cellData that's just the default state, but the object i care about saving most (Seed) i want to save all of its stats because they might be accessed in the future, and checking to see if it has the stat or not and then creating it would be more of a hassle than the few kb i save

swift falcon
lyric wadi
#

trying to pastebin an example

swift falcon
#

what's the byte[] data parameter supposed to be?
this is in the LoadData() function

string json = reader.ReadToEnd();
Data.Instance = JsonUtility.FromJson<Data>(json);
wintry crescent
#

I'm so annoyed
I have an object that has locked all movement and rotations blocked by rigidbody constraints (except for y rotation) but when I apply upwards torque to it, it still rotates a little bit along the other axes
why is it doing that?

lyric wadi
swift falcon
#

oh gotcha

#

try that rq

zinc parrot
#

With a raytracingaccelerationstructure how do you have it so objects inside it can move? UpdateInstanceTransform doesnt seem to work

swift falcon
lyric wadi
#

right on, that's just the process for gzip if you wanna use it, for me it took my saves from 100kb to 7kb from all the repeated data

swift falcon
#

damn

pearl swallow
#

This might be a more advanced question, but I just want to ask it here in case it isn't. So I have an enemy (GameObject) that fires a projectile towards the player's position due to following the player's position. How might I be able to adjust the height and/or speed so that the further the player goes, the further the projectile will go? This is how the current script works to instantiate and then add force to the projectile:

GameObject poison = Instantiate(poisonProj, poisonSpot.position, transform.rotation);
poison.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward*500);
swift falcon
#

what do you mean the further the player goes?

wintry crescent
pearl swallow
#

Yes

#

I do have a distance registry:

 playerDistance = Vector3.Distance(player.position, transform.position);

        if(playerDistance <= plantRange && plantStatus == 0)
        {
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));

            if (fireCountdown <= 0f)
            {
                GameObject poison = Instantiate(poisonProj, poisonSpot.position, transform.rotation);
                poison.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward*1000);

                fireCountdown = 10f / fireRate;
            }
            fireCountdown -= Time.deltaTime;
        }

But it is mainly in use to regulate that it fires within a certain range and to look at the player.

wintry crescent
# pearl swallow Yes

calculate the distance to the player, take its magnitude, then multiply the speed with that magnitude and some additional factor
you can also lerp between two values (min speed max speed) based on the distance and some max distance that you expect

wintry crescent
#

or something

#

and go from there

pearl swallow
#

So vector.forward*(100f *playerDistance)?

#

There's meant to be more of the stars-

#

God dammit discord

void anchor
#

return recur(recur(x * 3)); can anyone explain when a method replays in a method

pearl swallow
cosmic rain
wintry crescent
pearl swallow
#

Oh

#

Neat

pearl swallow
#

Thanks

wintry crescent
#

then you can look up things like Mathf.Lerp, Mathf.Clamp and other things

void anchor
#

idk what that means

wintry crescent
#

see what could be useful to you

#

especially Mathf.Lerp - you're gonna end up with this one, I almost guarantee it

pearl swallow
#

Alright.

#

I'll see if I can figure it out, otherwise I'll be back here.

cosmic rain
# void anchor idk what that means

It doesn't mean anything special. It's simply is called twice.
As for why it's done in that particular case, no clue. Need to research the code.

pearl swallow
#

Would a vector3.up also help it if its moving further away too?

#

In case terrain is uneven?

#

Or would turning off gravity or lowering gravity help?

lyric wadi
#

you can add vector3.up to the vector3.forward, you'll probably want to multiply it by magnitude as well in parentheses Vector3.forward + (Vector3.up * magnitude) * force * magnitude

wintry crescent
pearl swallow
#

If anything I might try to flatten the Terrain a tad.

lyric wadi
#

is this like a turret

pearl swallow
#

But I'll make sure to look back if I want to mess with it.

#

Kinda

#

It's a plant monster that shoots poison

#

So, effectively a turret

#

I'll mess around and play with it a little

#

I don't need it complete by tomorrow, just doing milestone presentation for the project.

#

I got next week free due to spring break

#

So I'll be deep diving if I don't get distracted with video games

#

*too distracted

wintry crescent
#

hi, is there a way, from inside the abstract MainMenuScreen class, call Register<ClassDerivingFromMainMenuScreen>() if my code looks like this?

public abstract class MainMenuScreen : MonoBehaviour
{
    private void Awake() 
    {
        Register<???>();
    }
    protected void Register<T>() where T : MainMenuScreen
    {
        MainMenuController.Instance.RegisterScreen<T>(this);
    }
}

I want every instance of a class that derives from mainmenuscreen to register itself automatically, while providing its own type

zinc parrot
#

Is there a way to have a #define in one file affect multiple other files without changing the settings?

buoyant crane
wintry crescent
mossy snow
#

why provide T at all? Register(this), get the type via GetType() inside RegisterScreen

wintry crescent
#

I ended up doing a screen.GetType() in the MainMenuController class

wintry crescent
mossy snow
#

I'd probably make Awake protected and virtual rather than have a separate Register method too, Awake is easy to shadow accidentally and then your register system will silently break

#

unless the derived type calls Register itself directly, which would be easy to forget

jolly dune
#

the problem is the if statment is asking for x or y

wintry crescent
#

is there a better way than just protected virtual?

#

it just squiggles a line right now, but does nothing about it otherwise

mossy snow
# jolly dune the problem is the if statment is asking for x or y

you could use clamp rather than an if statement, but this logic is weird. If either x or y velocity magnitude exceeds maxMovespeed, you set BOTH velocity directions to the max? So if I'm moving 1.1 units in x direction and 0.1 units in y direction with a max speed of 1, my new move speed should be (1, 1)?

faint brook
#

anyone know how to make drawray and drawlie stop flashing

wintry crescent
#

Hi - is there a way to load a scene, using LoadSceneAsync, but hold off the actual... enabling of the scene?
I want to load the scene, and when it's ready I want to do some things, then when I'm done - switch to it immediately, without loading or any further delay

vagrant agate
#

So.... I implemented a basic custom swipe. My dilemma now is, I have a few horizontal scroll containers on some of the views. I wonder what the best way is to detect if their finger started in any of the scrollable containers so it doesn't change screens on them.

cosmic rain
vagrant agate
cosmic rain
vagrant agate
# cosmic rain Not sure what you mean. I'd just have a script on each container, catching the p...

I was able to get it working using this. It detects if the mouse is over a scrollview by tag and stops my swipe code from running.

var pointerEventData = new PointerEventData(EventSystem.current) {position = touch.position};
        var raycastResults = new List<RaycastResult>();
        EventSystem.current.RaycastAll(pointerEventData, raycastResults);

        if (raycastResults.Count > 0)
        {
            foreach (var result in raycastResults)
            {
                if (result.gameObject.CompareTag("ScrollView")) return;
            }
        }
#

id say its probably expensive but my players wont be on this screen very much

cosmic rain
#

I'd use IPointerEnterHandler and it's friends.

dusty steppe
#

just clamp your degrees? before angleAxis

blissful frost
#

How do I put a variable from a script to a panel on my camera that changes (ammo)

oak plover
#

how would i go to making a attack animation when i have basic anim's for movement? i have basically no idea how to to do 2d anims lol

#

no i dont think i do

#

i dont know yet i want to see what is better for the game

#

bet thx mg

oak plover
#

m sorry what
im so confused
ignore flip and update animationstate but in my animation i have a bool named isAttacking from all states of anim if you press mb 0 it attacks so i made a pub void end attack. in side making "isAttacking" to be false. in the attack animation i set an event at the end making it so it stops the animation and going back to idle using a transition of isAttacking = false. the event is set up and this is too its staying in a constant loop.

https://hatebin.com/pjvqiscuql
heres the code

#

never mindddd

craggy veldt
solar kettle
#

hey could someone help me with an issue

swift falcon
solar kettle
#

I am having an issue with an editor script

swift falcon
#

What kind of issue?

#

Can you specify a little more

solar kettle
#

Its a lot to describe in chat

#

can I call you?

swift falcon
#

Uh not rn im in the bus going to school

solar kettle
#

Its from Natty's youtube series

#

I have a script that can be placed on some objects but not the one I need and it seems to delete the component right after I add it

swift falcon
#

Hm idk tbh

#

Just wait until someone thats knows a little more about this can help you

solar kettle
#

Its ok I figured it out

#

Its a custom editor script for interacting with objects

stable shore
#

pls help me

#

projects don't open

solar kettle
#

did u change the file path for your projects?

plucky inlet
# stable shore

not really coding related. but try to remove it and readd it in unity hub

stable shore
#

ok

stable shore
potent sleet
stable shore
#

idk

potent sleet
stable shore
#

ok I wont

#

after I fix my issue I will type in appropriate channels

fallen knot
#

Hi guys. I'm willing to pay someone to show me how to convert game object prefabs that have already been placed into my level, into Terrain Trees, while keeping their original locations, rotations and scales.
I'm a noob and have spent all day trying to figure this out. Is there a Job channel somewhere?

potent sleet
#

bot is taking a nap..

fallen knot
#

Thanks!

potent sleet
#

I think they got the opposite

#

they have prefabs and want to switch with terrain trees with same pos/rot/scale?

latent latch
#

Actually, that class seems rather useless. Doesn't really give any GO info.

#

beyond pos/rotation

plucky inlet
#

Well you can use this to place trees with the module based on the list of GOs transforms

latent latch
#

Oh, right so the terrain also changes the size and such as well too, so you can't really get all that information from the GO.

#

so you get the prototype and grab the size the terrain is changing it to.

plucky inlet
#

Not sure what you mean? He just wants to create trees on the already done terrain while using his gameobjects transform values. Nothing on the terrain is changing besides the terrainData holding the trees

latent latch
#

Oh, rofl. Ok, yeah probably an easier problem in this case then.

potent sleet
#

yeah hiring is prob overkill lol

latent latch
#

https://docs.unity3d.com/ScriptReference/TerrainData.SetTreeInstance.html
Well, this would seem like the func to use, but then there's this line

Sets the tree instance with new parameters at the specified index. However, you cannot change TreeInstance.prototypeIndex and TreeInstance.position. If you change them, the method throws an ArgumentException.

So, basically useless unless I'm understanding it wrong.

plucky inlet
latent latch
#

Ah, that's probably it then

fallen knot
#

What i want has to be very specific. Its not about instantiating my prefabs, its about getting them into the terrain tree system.
Because afterwards im converting the trees in the Terrain system into a plugin - but they need to be in the Terrain tree system first.
Im doing a conversion from Unreal to Unity

latent latch
#

Either way, you cant just init a tree onto the terrain, you need to assign it to the terrain first to give it the prototype. So, there's this extra bit of overhead.

#

optimization reasons I'd assume

fallen knot
#

The reason I'd be willing to pay for it, is because time is money, and im not adept at using Unity. Im barely even a beginner.
But Im a pro at Unreal, and i have a bunch of my Unreal assets on the marketplace that need converting to Unity.
I have an employee already doing this, but this the last issue in the pipeline that i need to resolve

#

If someone already knows how to do this, it'd make sense to just shoot through 10-20 bucks to just have the issue resolved, rather than spending countless hours trying to learn how to code.
Ive already spent 3 hours trying to search a solution to this online

#

I'd rather spend my time earning money doing what i do best, and just pay someone who is good at unity to solve it for me 🙂

latent latch
#

May be better off looking at the paid assets unity store has to offer

fallen knot
#

Im an Unreal Asset developer looking to convert my Unreal projects to Unity, to sell on the Unity store

#

actually, i see what you mean

#

If its a once-off thing and the code isnt in the product itself, that would be fine

orchid bane
#

I use this but the result position is only 1 unit far from the camera, how do I fix it?cs public void OnDrag(PointerEventData eventData) { transform.position = _cam.ScreenToWorldPoint(eventData.position) + _posDiff; }

eager cliff
plucky inlet
eager cliff
#

some projectile is flying to the top at start and some are flying downward

plucky inlet
# eager cliff

Ah, got it. So you need a start and endpoint and with those you gotta spread out the local values of the particles by using like a bezier animation curve that starts and ends at 0 and in the middle the spread as you like. from there you can randomize the spherical spread with that curve values to get the desired spreading effect.

#

You could also let them spread to the middle distance and then modify the particles from there to move towards the target back with simple lerping

eager cliff
#

its a animation thing? but not the actual gameObject movement?

#

I want the projectile hit enemy in the middle of flying if they touch the enemy

plucky inlet
#

So imagine you have a default line from A to B, that is your moving particle system or vfx origin. And with the time from start (0) to end (1) you can lerp the spread to be bigger at 0.5 and almost 0 at time 1.

eager cliff
#

so I want to code it but not just animate

plucky inlet
#

I would start using a particle system and read about how to access those and how to modify their position depending on the lifetime

#

Particle is always flying from point a to point b + the offset depending on the distance to the target.

crystal holly
#

hey guys, i'm pretty desperate at this point.. i'm trying to parse a json string containing mesh data. but for some reason i'm getting completely nonsensical values for all the vectors (vertices, positions..) the ones for the triangles are correct that's why i'm suspecting that something is being handles wrong with the floats..
my json string looks like this:
https://pastebin.com/snRZ5bck
but my parsed objects in unity look like this:

crystal holly
plucky inlet
#

How do you load your json and put it into class?

eager cliff
void fog
#

eg im pointing north, east, and west

#

once each projectile is fired, you'll need to basically "track" it back to target

#

to do that, you still do movment like normal but you're turning and other stuff

crystal holly
plucky inlet
eager cliff
#

I find a keyword "slerp". It's a upward curve, how do I get the left, right, and bottom slerp

void fog
crude mortar
plucky inlet
#

It is not

void fog
#

under the hood i assume it's using JsonSerializer.Deserialize<T>(string)

plucky inlet
void fog
#

why even have it then? lol

#

we dont even use newtonsoft anymore in .net core

void fog
eager cliff
void fog
#

moves?

eager cliff
#

so its always curving upward?

void fog
#

i think its more like finding points

#

eg. you have a dot at 0,0 and 10,10 and are connected via a curve

#

using interpolation would help you find points on that curve?

plucky inlet
void fog
#

there has to be a use case for it though

craggy veldt
#

STJ works in the latest version, no need to use the turtle newtonsoft

plucky inlet
#

unity is just nostalgic in keeping their own json utility in the software 😉

plucky inlet
void fog
#

System.Text.Json

plucky inlet
#

Ahhh, my bad 😄

orchid bane
#

How do I move a MonoBehaviour from one GameObject to another?

plucky inlet
plucky inlet
void fog
#

JsonConvert.Deserialize<T>(...)

craggy veldt
plucky inlet
crystal holly
orchid bane
craggy veldt
#

still much much better than the turtle newtonsoft

void fog
#

i still get them mixed up

plucky inlet
plucky inlet
void fog
#

if your .net version is 6+, you really should be using STJ

crystal holly
void fog
#

STJ is so much faster

craggy veldt
#

small memory footprint too

void fog
#

optimized code and a vastly improved framework

plucky inlet
#

Does it make a difference for one time calls tho?

void fog
#

its best to just get into the habit of using STJ

plucky inlet
void fog
#

and i did have it backwards damn it lol

#

JsonSerializer is STJ, JsonConvert is Newtonsoft

#
var options = new JsonSerializerOptions { WriteIndented = true };
            string jsonString = JsonSerializer.Serialize(weatherForecast, options);```
juice
#

oh now this is an interesting tidbit...

#

youd still have to convert those bytes to a string which might still be that 5-10% you're saving =/

#

whats the point?

craggy veldt
#

Note that you can still use STJ in the older Unity versions, it's just won't take the benefit of Span<T>

plucky inlet
# void fog whats the point?

Maybe using utf8 directly would benefit as you would not convert it, not sure. Someone gotta have a usage for that I guess 😄

void fog
#

this just gives you the encoding code instead of the actual string character

#

i guess that would be useful for when you are doing binary reads...

thin aurora
void fog
thin aurora
void fog
#

if you're running .net core, you have STJ

thin aurora
#

There is a Newtonsoft Unity package

thin aurora
void fog
#

the code-behind is C#

thin aurora
#

.NET != Mono

void fog
#

...

#

System.Text.Json has linux and macOS native methods

#

.net core is cross platform compatible

thin aurora
#

So how is this Unity compatible again?

void fog
#

because of the target framework of it's underlying language?

thin aurora
plucky inlet
#

From 2022 on you can use System.Text.String, so it can work

thin aurora
#

My question is how you expect a serializer that does not explicitly target .NET Standard to work in Unity

#

Unless, of course, I am mixing up the versions

void fog
#

.NET Standard is a formal specification of .NET APIs that are available on multiple .NET implementations. The motivation behind .NET Standard was to establish greater uniformity in the .NET ecosystem. .NET 5 and later versions adopt a different approach to establishing uniformity that eliminates the need for .NET Standard in most scenarios. However, if you want to share code between .NET Framework and any other .NET implementation, such as .NET Core, your library should target .NET Standard 2.0. No new versions of .NET Standard will be released, but .NET 5, .NET 6, and all future versions will continue to support .NET Standard 2.1 and earlier.

#

It's in .NET Standard 2.0 only for compatability with multiple target frameworks

#

.NET 4.6.1, .NET 4.8, .NET Core 2.1, 3.1, .NET 5/6/7/8/etc.

thin aurora
#

So how exactly would you make STJ work in Unity? Does the namespace exist in versions 2022 and later?

void fog
#

when your app compiles, it compiles against a target framework

#

.NET Standard is more of a "middleware" between versions for compatability

#

i reference .NET Standard libraries from my .NET 6 project and that has access to System.Text.Json

#

and newer versions of C#, etc.

plucky inlet
thin aurora
#

And this works without manually importing the dlls as plugins?

void fog
#

System.Text.Json has been a thing since .NET Core 3.1

#

You dont need additional nuget packages, correct

#

System.Text.Json is part of .NET inherently

thin aurora
#

That's different

void fog
#

just like Console.WriteLine

thin aurora
#

I know STJ is not a Nuget package

#

I'm talking about it being an actual part of Unity as of 2022

void fog
#

using System.Text.Json;

#

its not unity... its C#

#

unity just uses C#

plucky inlet
plucky inlet
void fog
#

?

#

in your code files where you put your logic, you cant put using System.Text.Json?

plucky inlet
#

System.Text.JSON is NOT part of unitys builtin NET version.

craggy veldt
#

^

plucky inlet
#

So you either have to hackaround, use newtonsoft or never look at json again 😄

void fog
#

STJ isnt compiled against .net standard 2.0

#

that means they restrict you to only standard 2.0

#

...

craggy veldt
#

just put the link.xml in your assets and make sure it won't get stripped when compiled

thin aurora
void fog
#

i think STJ would indeed add a dependency on having the .net 3.1 or later runtime installed

thin aurora
#

This is why I asked it

#

STJ is not in Unity

void fog
#

I didnt know unity locked things down like that

thin aurora
#

Welcome to Unity

void fog
#

im not writing things in the unity library

#

why do i need to stick to net standard 2.0?

#

im using the libraries... thats it

craggy veldt
void fog
#

theres no restriction from me working in a net 6 project and referencing .net standard 2.0 libraries

plucky inlet
#

Okay, I guess we just have to accept for now, the majority will use newtonsoft for now on Unity projects and from what I have seen, it works fine for everyone including me 😄

thin aurora
#

There is nothing wrong with Newtonsoft

void fog
#

except performance lol

thin aurora
#

People prefer STJ because it is buildin

#

But what they don't realise is that STJ does not actually compile for .NET Standard

thin aurora
#

And Mono supports .NET Standard, not .NET 5,6, whatever

#

So therefore my confusion as to why STJ is being suggested 😄

vague slate
#

I have 4 directions represented by simple vectors:
Vector2.up/right/left/down

I also have a quaternion which also represents such direction.
Question:
How do I rotate one of such directions with given quaternion?

For example if I have direction up (0,1)
and quaternion of angle (0,-90f,0)
I want to get (-1,0) result

plucky inlet
# void fog except performance lol

I think you taking edge cases as an example most people would not even run into if you dont do heavy reloading of data (which would be more of a problem of data handling then json itself)

thin aurora
#

There is a Newtonsoft Unity package and it's literally the same as STJ for more people

void fog
plucky inlet
thin aurora
void fog
#

the only reason they have mono is because of the graphics for linux and such

craggy veldt
void fog
#

mono works on net 6

thin aurora
void fog
thin aurora
#

I would appreciate STJ in Unity but as of right now you will have to deal with the mess that ended up because .NET was not cross platform back in the day

void fog
#

that jsonutility was their own homebrew

void fog
plucky inlet
# vague slate I guess

Did you try to just multiply it with your quaternion? cs vector = Quaternion.Euler(0, -90, 0) * vector;

void fog
#

the problem isnt .net... the problem is unity

#

unity is still using legacy mono functionality because linux still hasn't got a standardized graphics api

#

thats the only reason why unity is coded to still work against framework

#

framework is already or almost at EoL...

plucky inlet
#

Should this discussion be worth a thread to not clutter up the help channel? Just suggesting

void fog
#

threads have a tendency to kill conversations (which this is)

#

its not one person asking for support or anything like that

#

there's no one person in focus

cold parrot
void fog
#

hosting it . . it being what?

cold parrot
void fog
#

what native code?

cold parrot
#

The engine

void fog
#

the engine is written in C# and C++... DllImport and such lets you call the C++ from C#

#

i dont agree with what you're saying at all...

#

anything you can do in framework you can do and more, better with newer versions

#

unity hasn't been rewritten to work with the new language specifications... it's not .net lacking or missing functionality

#

its unity missing and lacking

plucky inlet
#

I think we got your point. I would suggest open a thread to keep on going about this thing, cause we are away from coding issues more into general unity implementation of features

void fog
#

this is general coding discussion

#

we dont need a thread

plucky inlet
#

you do you

cold parrot
# void fog i dont agree with what you're saying at all...

Something being technically possible doesn’t mean it’s immediately useful and all relevant situations are automatically solved. A lot of work has gone into making unity work with mono, these 17 years of development and design have to be recreated for core, and many past assumptions need to be changed and this has sweeping effects on a very large codebase

void fog
#

i think there is some miscommunication and/or misunderstanding

#

i can take a C# debugger and debug a unity game...

cold parrot
#

Parts of it

void fog
#

which parts can i not?

#

the C++ unless i have that debugger set up as well

cold parrot
#

The native parts

void fog
#

and the symbols

cold parrot
#

Which you don’t have

void fog
#

define "native parts" and please lets not use such ambiguous terms

#

lets be specific here please

cold parrot
#

The proprietary code that you have no source access to, or any debug symbols or documentation

void fog
#

for unity?

#

have you heard of dotPeek?

#

they dont even obfuscate it

#

that was part of my job at Curse... stripping assets from games like Hearthstone

#

the point is i can generate symbols for it and hit it with a debugger

cold parrot
#

great

#

Enjoy your life

plucky inlet
thin aurora
#

Sir I just wanted to inform you that STJ is currently incompatible with Unity 😢

void fog
modest ether
#

Does anyone know if there's a way to stream chunks of a big city mesh, not terrain? Or a way to divide one big mesh into smaller pieces? One way is to divide it yourself manually and stream chunks with sectr or world streamer.

cosmic rain
cold parrot
plucky inlet
#

you could also generate LODs if thats helping you stream fewer polygons, but why do you want to split it up in general? Does the user see it one after the other, or should it be dinstance based, what is the case?

cosmic rain
#

Maybe it's a trillion triangles or something 😅
And they need it to run on mobile🤔

plucky inlet
#

Isnt that a thing for occlusion culling then with as you said manual separation of the meshes? We will know it eventually 😄

modest ether