#archived-code-general

1 messages ยท Page 65 of 1

drowsy mortar
#

Not sure if there's any better place/channel to ask this, but im new at working with Unity, and one of my friends sent a script from a project he made, that uses Smooth Moves (Anim Plugin) AtlasTypes.SmoothMoves, Smooth Moves is deprecated (at least from what I've seen) and I don't own smooth moves, so I was wondering if there was any similar alternative for a smoothmoves atlas in any part of the C# section of the unity animation system (I added using UnityEngine.Animations;) that I could replace it with(I couldn't find any results while searching up some thoughts, also sorry if english is bad)?

cosmic rain
drowsy mortar
buoyant mural
ocean osprey
#

All of these sprites move at the same time, in the same direction.
But I want to know if there's any other way I could simplify this, instead of having a huge block of this, Could anyone help?

buoyant mural
#

Is this a list?

#

or all variables

ocean osprey
#

And is there any way I could move them at the same time in C#

buoyant mural
#

Yes

#

If you make an empty GameObject and then put these objects you want to move the empty GameObject's children or if you want it in code use lists or arrays then foreach

ocean osprey
buoyant mural
#

That's not good use:

buoyant mural
#
public List<GameObject> objects;```
#

or use

public GameObject[] objects;```
buoyant mural
#

it's easier

ocean osprey
#

ok

buoyant mural
#
foreach(GameObject objectToMove in objects)
{
    objectToMove.Move();
}```
buoyant mural
#

you could try using this but I highly suggest the empty GameObject method

ocean osprey
#

ok

#

I'll do that next

buoyant mural
#

The foreach method is very expensive

ocean osprey
#

Oh ok

buoyant mural
#

Just do this and move StuffToMove

ocean osprey
#

Yeah I'll do that

buoyant mural
#

So did it work?

#

Of course don't move UI with the rest of objects

ocean osprey
#

Wait

#

no its not your fault

#

I made a typo

#

It's working

#

Thanks

open lake
#

Hey

rotund burrow
#

i'm trying to use NavMesh.CalculatePath, but it returns false. i have a basic flat navmesh

hexed pecan
ancient rock
#

Hey, so currently I have two properties which detect the rotation around the horizontal and rotation around the vertical axis (respectively). How does one go about also making this happen for touch screens?

wet condor
#

in Truck Game
im trying to connect trailer with my truck
so i use configurable joint but i have few issues...

  1. my trailer is floating like balloon in starting lol (it get on ground when i move truck)
  2. my wheel colider bounce when it touch with other object
  3. my trailer just keep moving left and right the limit i have provided

Any Suggestions or Helpful material ? Anyone can suggest

rotund burrow
hexed pecan
hexed pecan
#

@rotund burrow How did you use it? Maybe you did something wrong

rotund burrow
#

NavMeshHit hit;
if (NavMesh.SamplePosition(transform.position, out hit, 100, groundMask))

hexed pecan
#

What is groundMask

#

Are you using a normal LayerMask?

rotund burrow
#

yes

hexed pecan
#

You need a NavMesh area mask

#

If you want every area then use NavMesh.AllAreas

#

Or GetAreaFromName if you have specific areas

rotund burrow
#

okay it works now, thanks

buoyant mural
#

@hexed pecan the code you gave me yesterday isn't really working

            Vector2 forward = new Vector2();
            forward.x = transform.forward.x;
            forward.y = transform.forward.z;
            Vector2 direction = destination.position - transform.position;
            float angle = Vector2.Angle(forward, direction);
            Debug.Log(angle);```
obsidian eagle
#

Hey, I'm new to Unity but more familiar with coding especially C#. So yesterday I started with my 4th project but there is something not right with my scene management. I created my project and added a canvas than in inspector menu I selected my main camera for render camera, render mode to Screen Space - Camera. Than added an Image background. Lastly I tried to add buttons but it seems that i can't click on them.

#

Also I added Box Collider 2D for the button. I don't think there is any overlays in the scene but again no idea why its giving me a problem. Because I have used UI buttons and OnMouseDown() method buttons and didn't get any problem like this. Any help will be appreciated ๐Ÿ™‚

hexed pecan
buoyant mural
hexed pecan
#

Why dont you use Vector3's like I suggested

buoyant mural
#

I did

#

today

#

got same result though

hexed pecan
#

How do you expect this to workcs Vector2 direction = destination.position - transform.position;

#

Those are Vector3's and you assign it to Vector2

buoyant mural
#

oh yeah

hexed pecan
#

I gave you very clear steps idk how you did it differently

#

And even suggested using Vec3 because its easier to understand in this context

buoyant mural
#

Ok turns out I tried using Vector3 wrong today my bad, now it's working when I did it right

hexed pecan
#

Read^

buoyant mural
#

It worked sadok

thin aurora
# ancient rock

What I would do it make this an instanced class, and have it implement an interface (for example IInputHandler) that enforces RotationAroundHorizontal and RotationAroundVertical. You can then make this class MouseInputHandler, and have a different one be TouchInputHandler. You then have a general manager to keep track of input, and depending on what input is used, it will assign one of the classes to a variable IInputHandler inputHandler;. You then get the values from this.

ancient rock
#

I didn't ask design choice advice...

#

I asked how do I get similar axis from touch input.

thin aurora
#

As in the methods?

plucky inlet
ancient rock
plucky inlet
#

Did you check the touch API from Input?

#

Is there an elegant way to target a specific value like position or rotation in a generic way? Imagine a static coroutine to call and modify by just throwing transform.position as value in it but also transform.scale for example?

hexed pecan
plucky inlet
# hexed pecan Can you show a pseudo-C# example of how you would use it?

Like this, so the second param would be the thing I want to modify.But maybe its just overcomplicating things and I should go with an enum. I just want a generic method to get rid of running coroutines for every animated class

this.AnimateScale(Easing.Ease.Spring, transform.position, Vector3.zero, Vector3.one * 5, 2);
hexed pecan
#

Hmm theres no way for it to automatically tell whether you are giving it euler angles, position, or scale

#

Youre using Scale in the method name but transform.position as argument, im a bit lost here

plucky inlet
#

Nah i just added the position for your reference of pseudo code, my bad. Just imagine its AnimatePosition()

#

I guess I might just go with an enum or three static functions to call scale, position or rotation and be good with that

hexed pecan
#

Normally you could pass it in as ref if I get what you mean but its not really possible with propeties like transform.position etc

plucky inlet
hexed pecan
#

Hmm can you add IEnumerators as extension methods?

#

Looks like it might be possible

plucky inlet
#

Just testing, again, ignore the position / scale naming issue ๐Ÿ˜‰

hexed pecan
#

I was thinking just a IEnumerator extension but with your way, with the intermediary MonoCoroutine you can store a reference to the coroutine so it seems good

#

So no, I cant think of a better way than that currently

plucky inlet
#

Alright, so I might just extend this to be able to have multiple coroutines as you can animate scale and position in parallel best case. Thanks for your feedback! ๐Ÿ™‚

tame zealot
#

Hello, how do you reference this question generator into the text component, im still not getting it, tq

plucky inlet
tame zealot
#

I have a button in the scene, when you click the button a new question will pop, from the text object that I placed

#

I already have the button working when you click it but its blank

plucky inlet
tame zealot
#

yay it works tq! .

plucky inlet
#

Anyone knows why a coroutine might not be started again after being stopped? The reference is correct, cause it stops it, but it does not start it again. Routine is an IENumerator

mono.StopCoroutine(iENumType.routine);
mono.StartCoroutine(iENumType.routine);
hexed pecan
plucky inlet
hexed pecan
#

I'm not sure how the StopCoroutine(IEnumerator) overload is supposed to work

#

But I know that StopCoroutine(Coroutine) works

plucky inlet
#

StopCoroutine is working fine on that, but not the start one

#

But only after I started the routine once, it tries to restart but only stops if possible

#

I assume the ienumerator kills itself after being done

hexed pecan
#

What if you try cs StopCoroutine(coroutineReference); coroutineReference = StartCoroutine(...);

plucky inlet
#

coroutineReference would be of type Coroutine in your case?

hexed pecan
#

Yea

#

Store it in the mono or something

plucky inlet
#

I tried that before, but let me try again. I observe that the function you create as an IENum might just be removed when done, so StartCoroutine(Animate(...));, the animate(...) is cleared after finished or stopped, let me test real quick

#

Hm, the object is still there

hexed pecan
#

Im reading the doc, am I the only one confused by this?

Note: Do not mix the three arguments. If a string is used as the argument in StartCoroutine, use the string in StopCoroutine. Similarly, use the
IEnumerator in both StartCoroutine and StopCoroutine. Finally, use StopCoroutine with the Coroutine used for creation.

plucky inlet
#

I think that is the three options you have, String, IENumerator or a Coroutine itself?

hexed pecan
#

Yeah but the last sentence says to stop it with Coroutine

plucky inlet
#

so string and ienumerator is the common way, nut sure about the Coroutine used for creation thing ๐Ÿ˜„

#

yeh, its confusing

#

I think they just call the IENumerator coroutine here

#

if you check the samples

#

oh well, you can stop a Coroutine with that type

hexed pecan
#

I always stopped coroutines with a Coroutine reference so thats the only one I know to work for a fact

hexed pecan
plucky inlet
#

Stopping always worked, let me refactor to start not the inumerator but set it to a coroutine reference

#

Argh... ๐Ÿ˜„ still not working

hexed pecan
#

Also how are you starting it currently

plucky inlet
#
 public class IENumType
        {
            public IENumType(AnimationType aT, IEnumerator r)
            {
                animationType = aT;
                routine = r;
            }

            public AnimationType animationType;
            public IEnumerator routine;
            public Coroutine coroutine;
        }
#
MonoCoroutine.IENumType monoCoroutineIENum = new MonoCoroutine.IENumType(animationType, Animation(monoCoroutine, animationType, easeType, startVector, targetVector3, duration));
monoCoroutineIENum.coroutine = mono.StartCoroutine(monoCoroutineIENum.routine);
#

the animationtype is just to separate position rotatino and scale lerping

#

Just found this with the right google terms...
You can't reuse the IEnumerator that is returned by a generator method. Such an IEnumerator can only be used once. You have to create a new one each time you want to start a coroutine. Also it's better to use the Coroutine instance that is returned by StartCoroutine to stop the coroutine.

hexed pecan
#

Ah so the problem is with passing around the IEnumerator?

plucky inlet
#

Yep, it just gets used and then gone, fire and forget ๐Ÿ˜„

#

well, I guess I just have to pass in the animate() thing everytime, also on restart

obsidian eagle
plucky inlet
#

Then I could not pass any values in ๐Ÿ˜‰

hexed pecan
#

Is this that one use case where it would make sense?

#

Oh right damnit

plucky inlet
leaden mural
#

Hello. I was wondering if somebody could help me with an issue with coroutines. I am trying to make it so whenever a certain coroutine is ran, it sets a bool to true, and then after 1 second, sets it back to false. However this coroutine only runs once, and I need it to run every time a bullet collides with an enemy. I tried finding a solution, and saw somewhere that I have to use a while loop to get it to run multiple times, but when I use a while loop, the bool never switches back to false after a second.

obsidian eagle
#

hey guys I have another question. When the button is clicked how can i get the text thats on the button? The button doesn't have any children component and it's using TMPro.

#

I'm trying to referance it by using

string nameItself = gameObject.GetComponent<TextMeshProUGUI>().text;

plush sparrow
#

I have 5 dice
Each containing a dice script that generates a random value
How do I collect the dice value from each of those dice

lyric barn
#

I have a question regarding tilemaps. So I have for example a room I painted, now I want to take that room and paint it somewhere through code, how do I do that?

hexed pecan
#

Or just one coroutine that loops?

#

The while loop is for repeating code inside one coroutine

neat hollow
#

[SOLVED] I had a random assebly definition script in project folder that didn't reference any scripts. So made new one and delete the random one at it worked. thanks for the assist

leaden mural
leaden ice
hexed pecan
#

Remove the while and put some logs inside the coroutine to see if it actually runs again or not

#

Make sure you dont get NRE or other errors in the console while playing too

leaden mural
#

Hmm. Debug.Log says the coroutine is running, but ran a Debug.Log on the boolean and it isn't switching back to true after the coroutine is started again.

hexed pecan
#

Which bool is that?

leaden mural
#

zombieKill. It sets to true once, and then after a second, turns back to false. But it stays false whenever it tries to run the coroutine again.

hexed pecan
#

Hmm. Are you sure that some other script isnt changing zombieKill?
The issue doesnt seem to be in the code you showed

obsidian eagle
leaden mural
leaden ice
#

what's going wrong

obsidian eagle
#

I attached this code to the button itslef

string nameItself = gameObject.GetComponent<TextMeshProUGUI>().text;

and I got this Error message that I don't how to solve

"Object reference not set to an instance of an object"

leaden ice
obsidian eagle
#

In my mind I'm referancing the object by calling gameObject

leaden ice
hexed pecan
obsidian eagle
leaden ice
obsidian eagle
thin aurora
leaden ice
# obsidian eagle

can you show the full error messge (with the line number) and the full Select Num script?

obsidian eagle
#

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class selectNum : MonoBehaviour
{
public string num;

public GameControl GameControl;

// Start is called before the first frame update
void Start()
{

}

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

public void getSelected() 
{
    string num = gameObject.GetComponent<TextMeshProUGUI>().text;
    //Debug.Log("done");
    //num = int.Parse(selectedNumberstr);
    GameControl.clickCount += 1;
    GameControl.newNumber(num);
}

}`

#

NullReferenceException: Object reference not set to an instance of an object
selectNum.getSelected () (at Assets/Scripts/selectNum.cs:30)
UnityEngine.Events.InvokableCall.Invoke () (at <4746c126b0b54f3b834845974d1a9190>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <4746c126b0b54f3b834845974d1a9190>:0)
UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:501)

obsidian eagle
thin aurora
tawny elkBOT
#
Posting code

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

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

leaden mural
leaden ice
#

you need to pay attention to your error message

#

it's because you haven't assigned GameControl

thin aurora
leaden ice
hexed pecan
leaden mural
#

Let me check

obsidian eagle
leaden ice
hexed pecan
#

To search by type

leaden ice
#

We've just showed you what your problem is @obsidian eagle and how to fix it. Good luck.

leaden mural
obsidian eagle
#

Alright, thanks...

thin aurora
obsidian eagle
#

how do I assign a script in the inspector?

leaden ice
obsidian eagle
#

no it's not an object it's a sciprt

leaden ice
#

it's a reference to an object that has a script attached to it

#

you must drop a GameObject which has the script attached to it into that slot

#

NOT the script itself

obsidian eagle
#

Still getting the same error. I know it's a pretty basic one but I've been trying to solve it for almost 2 hours

obsidian eagle
#

yes

leaden ice
#

then you will not be getting the same error

#

read your error carefully

#

it is probably slightly different now

#

Part of the reason you are working on this for so long is you did not read your error carefully. Remember you were looking at the wrong line of code for a while.

thin aurora
obsidian eagle
#

Alright I found the problem. I was clicking on the one that I didn't attached the game object to.

#

Thanks a lot guys

leaden mural
hexed pecan
#

Make one last check to see if anything uses the zombieKill bool (use your IDE's tools)

#

Ping me if you find the cause, maybe theres something I just cant think of right now ๐Ÿ˜„

tame zealot
#

Hello, can anyone help me, how to reference this script into a button?

dim spindle
#

by adding it to the button's event list

#

assuming you want that script to run every time you press a button

hexed pecan
tame zealot
dim spindle
#

by passing a ref to the text

#

and then .text on that ref

tame zealot
#

is it somthing like this?

#

answerText_1.GetComponentInChildren<Text>().text = answerChoices.ToString();

subtle herald
#

Well you don't want to pass the entire list. Presumably you'd only want a single value from it.

#

Nvm, I see what you're doing I think. So you'll just want to concatenate them or something else.

tame zealot
#

Im trying to make a simple math game and cant figure how to get button to change

vagrant agate
#

Does FindObjectOfType start top down in hierarchy ? I'm wondering if its an issue using it only for finding my canvas component. It sits at the very top of the hierarchy. I'm only calling it when spawning a popup prefab to assign it to the canvas transform.

#

performance wise

mystic ferry
#

that said, FindObjectOfType is one of the worst, least performant ways to fill a dependency

vagrant agate
leaden ice
vagrant agate
#

In my game , I only have around 200 GO's at any given time. Do you think it would be a problem finding the canvas using that method ? It is only to spawn dynamic popups for tutorials.

#

It may not even be that many GO's

mystic ferry
#

if you cache a reference to it, it's not THAT bad. As long as you aren't calling it in Update or something

#

still, it might be better to have a field in a manager class filled with an Instantiate or something

#

just keep an eye on the profiler when you build it. If that's causing the issues, refactor it

vagrant agate
#

I cant really cache it in my manager since the tutorials happen even after scene change

mystic ferry
#

do your managers not persist through scenes?

vagrant agate
#

they do but i'm using a utility DDOL class to spawn my popup prefab which finds the canvas in whatever scene its in

leaden ice
vagrant agate
#

when the scene changes..the canvas does also.. So you can't cache the object of my canvas once its found the first time

leaden ice
#

that's all you need, no?

vagrant agate
#

Nah, I have my Utility Class DDOL singleton <~~ that has a method that spawns a popup prefab which also has a WindowPopup Script.. It needs to find the canvas no matter what scene it is in so I can parent the popup to the canvas transform

leaden ice
#

you could also just make the canvas DDOL

#

especially if it's a popup - it should probably have its own canvas

rain minnow
#

Or does the canvas not persist through scenes?

vagrant agate
vagrant agate
rain minnow
vagrant agate
#

Ill try that and see what happens

rain minnow
#

You should have separate canvases for different UI where necessary to avoid redrawing canvases . . .

vagrant agate
#

You make a great point

#

well I have a few days of refactoring now... lol

sweet raft
#

Is there a way to give a name to an Array Element (that shows up in the Inspector), without going the route of making a struct to hold the Element data and making the first variable of that struct a string? For example, if the Array is an Array of ScriptableObjects, and you just want the Element name to be the name of the created ScriptableObject.

leaden ice
sweet raft
soft wave
#

I'm trying to implement portals and I'm very confused on how to implement the object cloning
I need to create a copy of the object being teleported that is put at the other portal until teleportation is done, but just instantiating a copy seems too complicated
I'd have to remove all of the scripts but also find a way to keep animation working
Does anyone have a good approach?

leaden ice
#

with all the stuff set up on it

#

and show it in the right place/right time when necessary

#

otherwise hide it

outer plinth
#

When combining meshes with CombineMeshes, are there certain rules that need to be followed to allow the meshes to combine?? I'm almost certain I'm not doing anything wrong but I can get it to work at all

#

These are the meshes in question

#

Like can I only combine meshes that contain no space or do the triangles and vertices have to all meet together??

thick socket
#
        for (int i = 0; i < numStars; i++)
        {
            var tmpStar = starsList[i];
            tmpStar.style.backgroundImage = new StyleBackground(starsFull);
        }
        for (int i = numStars; i < 5; i++)
        {
            var tmpStar = starsList[i];
            tmpStar.style.backgroundImage = new StyleBackground(starsEmpty);
        }

vs

#
for (int i = 0; i < 5; i++)
{
    var tmpStar = starsList[i];
    if (i < numStars)
    {
        tmpStar.style.backgroundImage = new StyleBackground(starsFull);
    }
    else
    {
        tmpStar.style.backgroundImage = new StyleBackground(starsEmpty);
    }
}
#

which should I be doing?

#

Im guessing 1 for statement with the int but not sure

mellow sigil
#
for (int i = 0; i < 5; i++)
{
    var tmpStar = starsList[i];
    var bg = i < numStars ? starsFull : starsEmpty;
    tmpStar.style.backgroundImage = new StyleBackground(bg);
}
outer plinth
#

Ah nvm fixed

thick socket
primal solstice
#

does any one know how to make my character not float when he goes off the map?

sterile crown
#

add a ridgidbody with physics enabled

#

you need gravity scale to be larger than 0

granite nimbus
#

is there a better way in C# to return multiple values from a method than just packing them into a struct / using ref or out?

#

something more convenient, maybe like
public (int, bool) Method()
idk

thick socket
#

pretty much your choice is tuple or struct/class

granite nimbus
#

oh right, this is really cool

#

thanks

cobalt flint
#

Is GetComponent considered FindObjectOfType during runtime?

granite nimbus
granite nimbus
#

it may be worth doing a struct if you return many many values, but for two or three, I think it's tuples

#

but if you return many values, maybe you're doing something wrong with your method๐Ÿ˜€

rain minnow
rain minnow
granite nimbus
rain minnow
plush sparrow
#

How can I lock the value of a variable after changing it once?

#

So that it can't be changed again

leaden ice
plush sparrow
#

There are many variables
Which I have to control individually

#

Bool approach is not appropriate

leaden ice
#

use a bool for each one

#

or

#

make a type that contains your value and a bool and change your variables to this type

#

or asasign these values in a constructor and make them readonly

cobalt flint
# rain minnow Nope, not the same thing . . .

I didn't think so. I'm trying to understand why I'm seeing "FindObjectOfType" in my profiler during runtime, when nothing ever calls that except in start/initialize. LONG after the game has starting basically its showing up

plush sparrow
#

Cannot make them readonly
As I have to change them for a certain amount of times

cosmic rain
leaden ice
#

or better yet - explain what you're actually trying to do so we can recommend a sensible solution

plush sparrow
#

Oh

#

Like I have some combination of dice

#

5 dice

#

I roll them until I find a specific combination
I am updating the total after every roll

#

But once I lock the combination
I don't want the total to change

plush sparrow
#

5 dice with 13 things that can be locked or not locked

#

Is bool the correct way?

leaden ice
#
struct thing {
  int value;
  bool isLocked;
}```
plush sparrow
#

Oh

#

Thanks

stuck robin
#

hmm so this probably sounds dumb but I made my own input field class, as I found the input field also acted liked a scroll rect and I needed it parented to a scroll rect, so it was double scrolling. But now I'm having issues with implementing the selection caret -_-

#

one problem for another lol

#

like tracking the user pos is easy enough, but I can't figure out how to create the actual caret. do I add a | pipe to the end of the .text component? use a rectangle graphic bar thing? or something else

near wagon
#

?

stuck robin
#

I guess I could skip the selection caret, but that presents a design problem in regards to text input as this is for an in-game code editor

stuck robin
#

i was using the textmeshprougui class for the text components, so whatever that is

ebon pendant
#

does anyone know roughly what this error means?

stuck robin
#

I think with the legacy text components you can call methods on the vertices of the text mesh and get info that way to render the caret but Im not sure what the equiv methods are for TMP

near wagon
#

help please?

leaden ice
ebon pendant
#

oh lol

#

thanks

polar marten
near wagon
#

anyone?

placid ridge
#

I'm having issues scaling my collider to 0.5 scale, and i've been having trouble figuring out the colliders, i set the cell size to 0.5 any ideas?

swift falcon
#

if someone can help me why am I unable to transform that string into a date?

mellow sigil
#

not without seeing the code

swift falcon
#

I thought try parse would parse the 2nd format

leaden ice
swift falcon
#

i can show you the debugs and code but it is not working

leaden ice
swift falcon
leaden ice
#

you need to make sure you are checking the return value of TryParse

swift falcon
leaden ice
#
if (DateTime.TryParse(...)) {

}
else {
  Debug.Log("Could not parse input string");
}```
leaden ice
swift falcon
leaden ice
swift falcon
#

ok ill check the link

#

thank you

ruby trellis
#

Hello! I'm making a space game and I need a UI to tell you your velocity relative to the planet and I need to do it per axis so the player knows in what direction the planet is moving in relative towards the player. The problem is the planet and the player don't have a Rigidbody so I need to calculate their speed themselves. This is what I have so far it only calculates the total speed and I cant figure out how to do it per axis (Relative to the player of course).

float distance = Vector3.Distance(currentPosition, targetPosition);
float lastDistance = Vector3.Distance(lastPosition, targetPosition);

float velocity = (lastDistance - distance) / Time.deltaTime * 10;
lastPosition = currentPosition;  

The video is to show what this should look like in gam (Sorry for the Programmer art and the cool spinny move at the end).

west sparrow
# ruby trellis Hello! I'm making a space game and I need a UI to tell you your velocity relativ...

I'd probably tackle it another way

Public Vector3 LastDist;

private void Update() {

  // How far are we from each other?
  Vector3 dist = that.Transform.Position - this.Transform.Postion;

  // Do we have a distance stored? If not, we need to do this or it will give us a weird number on the first frame
  if(LastDist == Vector.zero) 
    LastDist = dist;

  // Now, what is the distance we've moved since the last frame?
  Vector3 diff = dist - LastDist;

  // Now multiply it by how long it has been in seconds to get the meters per second
  Vector3 speed = diff / Time.deltaTime; // speed is the value you care about here

  // Now that we have the speed, we can store our new distance for the next check to verify against
  LastDist = dist;
}

Something simple like that should get the meters per second, in the X, Y, Z of a Vector3.

ruby trellis
#

Oh interesting, thank you let me just try that out

#

ah thanks for the edits

west sparrow
#

No problem, it's from my phone, so hopefully close enough to help

plush sparrow
#

I have 5 objects containing the same script

#

I want to call a method in that script from another script attached to another object

#

How do I do that other than referencing all the gameobjects individually?

vagrant blade
#

Create a [SerializeField] TheObjecType MyObject; and drag it in.

#

That's assuming the other object and the one you want to call it on exist in the editor.

#

If not, then you need a way to identify it. But that depends on when you want to call something on it (such as when you collide with it for example)

plush sparrow
#

How will the serializefield help?

#

I have multiple gameobjects containing the script

vagrant blade
#

You can drag the one object you want to call on it.

plush sparrow
#

And I want to refer a method in that script that should affect all the objects

#

Ah I don't want one object
I want all the objects to reflect the changes

tame zealot
#

Can anyone help me, if I press enter on an empty input field it keeps giving an error

vagrant blade
#

If the function has to run on all, you could use a static function. If that doesn't suit your needs and you don't want to reference all the objects in a list and iterate through them, you could consider invoking a function from the other object which all the same ones listen for and handle the results in their own way.

vagrant blade
simple egret
#

Or use int.TryParse() which returns a bool value indicating whether the conversion was successful or not

#

You get the parsed number (if successful) in an out parameter

leaden ice
#

!collab

tawny elkBOT
tame zealot
ruby trellis
wide fiber
#
void Moving()
{
  if (isGrounded)
        {
            movement *= speed;
        }
        else if (isGrounded == false)
        {
            movement *= 0;
        }
    }
}
    //------------JUMP------------------------
    private void CheckGrounded()
    {
        isGrounded = Physics.CheckBox(transform.position, boxCastSize / 2f, Quaternion.identity, groundLayer);
    }
    private void Jumping()
    {
        if (isGrounded && p_input.jumpInput)
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }

    }```

Why when my isGrounded = false, my speed didn't switch to 0?
west sparrow
wide fiber
# west sparrow Is `Moving()` even being executed?

sorry this is the full code.

 movement = p_input.xAxis * transform.right + p_input.zAxis * transform.forward;
        movement *= speed;
        movement += new Vector3(0, rb.velocity.y, 0);
        if (rb.velocity.y < 0)
        {
            movement += Vector3.up * Physics.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
        }
        rb.velocity = movement;

        if (isGrounded)
        {
            movement *= speed;
        }
        else if (isGrounded == false)
        {
            movement *= 0;
        }```

Basically just disable the controls when jumping so my player wont feel floaty ๐Ÿ˜„
leaden ice
west sparrow
#

Yeah

#

What they said ๐Ÿ˜„

vagrant agate
#

So how do I get an exact position of a nested canvas UI element so that when I set its parent to null, I can set its position back to where it was?

wide fiber
#

oh ok. thanks so much for the clue @leaden ice @west sparrow !!

simple egret
vagrant agate
somber steeple
#
    {

        StopCoroutine(ShakeCoroutine(0));

        // Move the spike downwards
        Vector2 dropPosition = transform.position;
        dropPosition.y -= dropSpeed * Time.deltaTime;
        transform.position = dropPosition; I
    } ```  I am dropping a spike when a player is near it. It does have a Rigidbody2D attached it and a collision detection. It's supposed to stop the moment it touches the ground, but sometimes it goes a bit further into the ground before stopping depending on whether the collision happens in between frames. I do have continuous and interpolate enables
leaden ice
#

what's this about?
dropPosition.y -= dropSpeed * Time.deltaTime;

vagrant agate
#

nested object inside canvas > change parent to canvas transform using set parent. that is what im trying to do but it shifts to the left side of the screen

leaden ice
#

Also what's this for?
StopCoroutine(ShakeCoroutine(0)); < this almost certainly is not correct

somber steeple
leaden ice
#

Where is this running from? Update?

#

It should be in FixedUpdate if you're trying to do physics

#

in fact you should just give it a Rigidbody and a velocity and let the physics engine move it

somber steeple
#
    {
        if (!willFall)
        {
            return;
        }

        if (CheckDistanceX() < noticeDistanceX && CheckDistanceY() < noticeDistanceY)
        {
            if (!isTriggered)
            {
                int numShakes = activeOnFirstRay ? 1 : 2;
                StartCoroutine(nameof(ShakeCoroutine), numShakes);
            }
        }

        SeePlayer();
        // Check if the spike is triggered and hasn't already dropped
        if (isTriggered)
        {
            DropSpike();
        }
    }
rigid island
#

Anyone here good with Hex based grids could help me ?
I've been stuck here for a few weeks no Idea how to move forward with this...
Currently have a neighbor detector with my tile, and it works fine, I'm trying to expand it to include my attack range but all my experiments it turns into a weird shapes..
the math is kicking my ass rn
My Current result from my script is the first two images which is fine(red tiles are the current script)

#

Current script, not much going on ```cs
void Start()
{
Vector3Int[] neighbors = startPos.neighbors();

    foreach (Vector3Int neighbor in neighbors)
    {
        tilemap.SetTile(neighbor, highlightTile);
    }
}```
#

I'm using unity's tilemap so all the solutions on RedBlogGames are not translating correct

#

I hand drew it in tilemap but this is something I'm trying to do with current scripts

ebon pendant
#

What could these be from?

#

They don't point to any specific script being the problem

leaden ice
#

it's true though that Unity's cell coordinates are weird

#

but it seems like your neighbors() function works

#

so you should be ok

leaden ice
#

if you're not using the job system it's likely an internal unity thing

ebon pendant
#

thanks, just wanted to make sure it wasn't me

rigid island
leaden ice
leaden ice
rigid island
#

trust me I read through it multiple times and also tried some conversion formulas from RedBlogGames but it goes beyond my tiny monkey brain

leaden ice
#

This looks wrong I think
public static Vector3Int southeast(this Vector3Int vector) { return vector.y % 2 == 0 ? vector + Vector3Int.down : vector + Vector3Int.down + Vector3Int.right; }

#

wait sorry

#

misread it

#

thought that was southwest

rigid island
#

it's ok, was about to say lol It does work fine esp when I use it with A* pathing but have no clue on how to expand outward in a circle

leaden ice
#

ok I think your neighbors code looks good (though it might be very gc heavy with all the new arrays

#

so it's just a matter of doing a limited-depth search then, right?

rigid island
#

is Activity a custom class ? does it have System.Serializable

leaden ice
hexed pecan
leaden ice
#

I definitely forgot to add results to the results list in that sample code, and return the list

#

but should be simple enough to add

#

Once you've got a neighbors() function that works, it just comes down to standard graph-based algorithms

rigid island
rigid island
#

Think something like X-Com and stuff

#

but hex, which is making this super annoying (unity tile system grid is weird)

#

Wait............

#

I think it's working

#

dam @leaden ice I think you literally solved this in like 5 minutes

mystic ferry
#

having a strange issue where one of my events seems to be firing twice per button press. I unsubscribe the listener before subscribing it just to make sure the event isn't somehow subscribing twice, and it isn't

#

I guess the event is firing twice per frame?

rigid island
mystic ferry
#

but I don't know why. All of my other events work fine

rigid island
#

โค๏ธ much love @leaden ice You smart

leaden ice
rotund burrow
#

how should i approach making an ai unit with custom movement jump on a navmesh? say jump is just adding some velocity to rigidbody

rigid island
hexed pecan
leaden ice
hexed pecan
#

It's not really spatial pathfinding like usual

#

But nodes that consist of actions and conditions

leaden ice
#

Isn't it more like how a mouse does pathfinding

#

without global knowledge of the space

hexed pecan
#

Theres a world state that I feed parameters into and that is all the agent knows

leaden ice
#

So machine learning?

hexed pecan
#

It wants to satisfy a certain goal/condition, like for example HEALTH >= 100
Then it searches through the graph to find actions that will lead into satisfying that goal by checking the resulting world state
I'm thinking it would find an action that satisfies the goal, and find the "shortest path" to it, but I wont use only distance to calculate the costs but also the cost of the actions and how well they satisfy the desired world state

thick socket
#

if I do rnd.Next(10)

#

will I get number 0,1,2,3....9,10?

#

or if one of those missing

hexed pecan
#

Just for NPC behaviours

#

I'm still kind of wrapping my head around the whole idea

leaden ice
#

Not familiar with it

hexed pecan
#

Alright, was worth a shot heh.

#

Damn I wish the AI channel was more active and not all the way down there

thick socket
hexed pecan
#

Yeah ๐Ÿค” Most questions seem to be about using the NavMesh but thats probably because its not in the code category

thick socket
#

yeah, I think it includes the min and not the max from what Im seeing

#

so Next(10) is 0-9

hexed pecan
#

Yeah apparently the doc says it is exclusive upper bound

#

So 0-9

#

Just like unity's Random.Range int version

thick socket
hexed pecan
#

The main difference is that UnityEngine.Random is a static class, but with System.Random you use instances of the class

#

If thats what you were asking

thick socket
#

gotcha...why would I use one over the other

hexed pecan
#

If you have multiple objects and want them to use their own seeds without messing with each other, you would go with System.Random because you can make instances of it

thick socket
#

gotcha thx

tame zealot
#

Is there a way I can stop object movement after lets say > 2 seconds ?

strange epoch
potent sleet
thick socket
#

I was gunna say collider checks, but Null is probably right

tame zealot
#

simple ones

potent sleet
#

or set speed to 0

thick socket
#

can start a coroutine that waits 2s

#

then sets the bool

sharp blaze
#

Is it possible using a corountine to slowly spawn a prefab and its objects and also add like a progress bar to it or something?

hoary sparrow
sharp blaze
#

So If I have one prefab with many meshes/objects inside of it how would I do it

#

?

#

Get all the children of the prefab

#

And then spawn the all one by one?

#

In the corountine?

hoary sparrow
#

that could be one way to do so

sharp blaze
#

Do you maybe have a better way in mind?

#

Im open to all ways xD

strange epoch
hoary sparrow
sharp blaze
#

Nono its more of like a smaller map prefab loading for the player

#

I know I could use additive scenes but

#

Im also doing networking so it kinda messes up stuff a little bit

#

So doing it with prefabs would be an okay solution

hexed pecan
hoary sparrow
sharp blaze
#

Alright, thank you a lot!

strange epoch
hexed pecan
#

Probably shouldnt matter, but I cant say for sure

#

At least the doc doesnt mention anything about it. It just needs two Collider2D's - which TilemapCollider2D is as far as I know

green lily
#

Hey, is there any way to create some sort of global public static gameObject that holds static values like say, int health and int currency that can interact with gameobjects in the scene but can be called without having to directly reference said GameObject instance? I want to store these values in some sort of global "GameState" manager that uses properties to automatically call what happens when the player takes damage (like updating the UI, playing sound effects, etc) but I don't want to fill my code with a bunch of boilerplate that locates said instance or have to manually drag around and place a GameState instance into every single component that needs it.

somber nacelle
#

it sounds like you want a singleton. but it also sounds like you want that singleton to do too much

green lily
#

well i just want it to call functions on other objects when the properties it holds are changed

somber nacelle
#

you should look into events and/or the observer pattern

green lily
#

alr i will

mystic ferry
#

if I have two canvas elements for UI and I want to flip between the two (like between a main menu and an options menu for example), what is the difference between enabling and disabling the parent GameObjects of those canvases, and just enabling/disabling the canvas components themselves?

#

functionally they seem equivalent, does it have any other effects I'm not seeing?

marble halo
#

trying to remember if unity 2d supports capsule colliders

#

it does

mystic ferry
somber nacelle
#

just build to a different folder, it's literally that simple (or move prev build to a different folder before building)

#

just note that it's faster to build upon a previous build than doing a full clean build

pine bronze
#

hey guys, i want to make my character controller jump but when i press space to jump, it teleports me to the jumpForce and then fall down because of gravity. did i do anything wrong?
jump method

    public void Jump(InputAction.CallbackContext context)
    {
        if (canJump)
        {
            Debug.Log($"{movement.x},{movement.y},{movement.z}");
            if (controller.isGrounded)
            {
                movement.y = jumpForce;
                controller.Move(movement);
            }
        }
    }

where i apply gravity

    public void ApplyGravitation()
    {
        if (useGravity)
        {
            if (!controller.isGrounded)
            {
                movement.y -= gravity;
            }
            controller.Move(movement * Time.deltaTime);
        }
    }
strange epoch
#

I think you are setting the position directly rather than the speed.

pine bronze
#

should i set the y velocity of the controller?

strange epoch
#

The easiest way is to use a rigidbody, and changing the rigidbody's speed

pine bronze
strange epoch
#

I'm not used to using the character controller, so I'm not really sure. Sorry

strange epoch
hexed pecan
#

If phys2d.distance gives you a negative value when the colliders overlap, maybe you can use that distance to separate them? After making it positive ofc

#

But again im not sure how that particular method works, just saw it mentioned in a thread. Might test it tomorrow

marble halo
#

Ok so for some reason when im on a slope too steep to step and im pushing the move keys the character wont slide down

ashen yoke
#

anyone has a hack to open arbitrary cs file in IDE from editor?

#

nvm they are all MonoScript

granite nimbus
#

when I do foreach for NativeHashMap / Dictionary, in which order does the loop go through? Is it defined even?

ashen yoke
#

should be in sources

#

IEnumerator in the collection file

#

my guess its lower to higher

granite nimbus
ashen yoke
#

hash

#

hash is an int

#

Vector3 hashes to an int with spookyhash

#

youre doing spatial hashing?

granite nimbus
#

all I needed to know is it's a defined consistent behaviour

ashen yoke
#

you wont get that, v3 (3812,898,1) can be some -83671289291 int

#

+1 to it and you get 7772812391

#

getting data out of spatial hashmap means you have to lookup every time using same key

granite nimbus
#

then I need to store index in my value

tepid river
ashen yoke
#

haha

granite nimbus
ashen yoke
#

that means sorting every time you want to iterate?

#

or just having the position available

granite nimbus
ashen yoke
#

yeah this smells like xyproblem

tepid river
#

just keep a separate array of the values for iteration

#

hashmaps are for lookup, not having an order ๐Ÿคทโ€โ™‚๏ธ

tame zealot
#

Could someone help me with this, the top if statement is fine but the bottom one starts as soon as I press play how do I make this work?

granite nimbus
tepid river
#

if (!someFlagThatWasNotSetYet)
return;
?

ashen yoke
#

first condition not satisfied, it jumps to second, thats all that happens

tame zealot
#

when I put the answer, the if statement works fine but the else if statement just starts without even me putting in the answer.

ashen yoke
#

second if() is not necessary, else is enough

#

yes because its in Update()

#

its called every frame

granite nimbus
tepid river
#

the logic does exactly what its build to do.
on every frame, do something with the answers.
if correct do this
if not correct do that

#

if you want it to wait until you do something elsewhere, you need to build your logic to reflect that, f.e. with a boolean flag

granite nimbus
tame zealot
#

yes it's just a simple math game, I put the correct answer Sprite moves forward. Wrong answer, sprite moves backward.

tepid river
#

then have your logic wait until there is an answer

buoyant crane
granite nimbus
#

can also more conveniently define answer as nullable and check if answer != null

ashen yoke
#

best to hook up a button to check

wooden horizon
#

hey can anyone help me with name spaces and scriptable objects? im using version 2021.2.91f and ive followed many tutorials but none of the have worked. This keeps appearing and i cant create any scriptable objects via the the project content browser. I just cant get custom name spaces to work for some reason

tidal shadow
#

i have these cables that i gave an electrical effect (runtime executed) and they are bent as you can see
i got a nice curve on geogebra using 0.01x^2
how would i apply that simple formula to get new checkpoints along each cable?
code i already have (not done with above idea in mind)

    public void Initiate(GameObject effect, Vector3 pos1, Vector3 pos2, float positionsBetween, float positionOffset)
    {
        this.effect = effect;
        this.pos1 = pos1;
        this.pos2 = pos2;
        this.positionsBetween = positionsBetween;
        this.positionOffset = positionOffset;

        direction = pos2 - pos1;

        CreateEffects();
    }

    void CreateEffects()
    {
        Vector3 length = direction / positionsBetween;
        GameObject? latestEffect = null;

        for (int i = 0; i < positionsBetween+2; i++)
        {
            positions.Add(pos1 + length * i);
            latestEffect = Instantiate(effect);
            effects.Add(latestEffect);
        }

        effects.RemoveAt(effects.Count - 1);
        Destroy(latestEffect);
    }

    public void UpdateEffect()
    {
        List<Vector3> randomOffsets = new List<Vector3>();

        randomOffsets.Add(pos1);
        for (int i = 1; i < positions.Count - 1; i++)
        {
            randomOffsets.Add(positions[i] + new Vector3(Random.Range(positionOffset, positionOffset), Random.Range(-positionOffset, positionOffset), Random.Range(-positionOffset, positionOffset)));
        }
        randomOffsets.Add(pos2);

        for (int i = 0; i < randomOffsets.Count - 1; i++)
        {
            Vector3 halfWay = (randomOffsets[i + 1] - randomOffsets[i]) / 2;
            effects[i].transform.position = randomOffsets[i] + halfWay;
            effects[i].transform.LookAt(randomOffsets[i + 1]);
            effects[i].transform.localScale = new Vector3(0.05f, 0.05f, (randomOffsets[i] - randomOffsets[i + 1]).magnitude);
        }
    }
mystic ferry
#

if I have two canvas elements for UI and I want to flip between the two (like between a main menu and an options menu for example), what is the difference between enabling and disabling the parent GameObjects of those canvases, and just enabling/disabling the canvas components themselves?

#

functionally they seem equivalent, outside of obviously the different methods you use to interact with them

tidal shadow
restive flame
#

i have this nre but it doesnt show anything when double clikcing it, can someone help

swift falcon
#

I get value of variable isGrounded every frame, which i refer to in another method that gets called elsewhere.

    void Update()
    {
        isGrounded = controller.isGrounded;
    }
    private void applyGravity()
    {
        if (isGrounded && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }
        playerVelocity.y += gravityConstant * Time.deltaTime;
    }

But is it necessary for me to have that line in Update()?
Could I instead do

    void Update()
    {

    }
    private void applyGravity()
    {
        if (controller.isGrounded && playerVelocity.y < 0) // <---- here
        {
            playerVelocity.y = 0f;
        }
        playerVelocity.y += gravityConstant * Time.deltaTime;
    }```
Is that mechanically equivalent?
somber nacelle
#

it really depends on when you are calling CharacterController.Move since that is when the CC's isGrounded property is updated

swift falcon
somber nacelle
#

yes

swift falcon
#

hm

#

is it recommended to even use CharacterController?

#

why not just implement movement myself in my own script

somber nacelle
#

you can, there's nothing wrong with that. you just need to understand how it works and how its isGrounded property works if you aren't ground checking manually

fluid lily
#

I am getting the fallowing error.
The type or namespace name 'Fog' could not be found (are you missing a using directive or an assembly reference?)

#

Any idea what assembly to add to mine to use this?

somber nacelle
fluid lily
#

Context.

source = GetComponent<Volume>();
source.sharedProfile.TryGet<Fog>(out var fog);
quartz folio
fluid lily
swift falcon
#

Why does this guy make a Vector3 when the input is a vector2?

#

Does CharacterController.move() just require that?

fluid lily
#

this is my first attempt so not sure how to go about it.

fluid lily
quartz folio
fluid lily
#

yes

quartz folio
#

Well, unless I'm mistaken it's not a default effect

#

Either way, your IDE should be able to autocomplete or at least suggest the namespace that you are probably missing

fluid lily
#

It is not,,, Though I have an assembly definition that the script is in that I am assuming I am missing(and why my IDE isn't seeing it).

quartz folio
quartz folio
fluid lily
#

Yeah it isn't auto getting the Fog namespace. My FogController script is under MyCustomNamespace which is encapsulated by an assembly definition in unity. So for example I had to add an assembly for it to see the Volume type under.

quartz folio
#

Can you search for Fog in your project and find out where it is? Because my URP does not have a Fog volume effect, so there's no way to help you

swift falcon
#

This seems like inconsistent code

public class InputManager : MonoBehaviour
{
    private PlayerInput playerInput;
    private PlayerMotor playerMotor;

    void Awake()
    {
        playerInput = new PlayerInput();
        playerMotor = GetComponent<PlayerMotor>();
        playerInput.OnFoot.Jump.performed += context => playerMotor.Jump();
    }

    void FixedUpdate()
    {
        Vector2 input = playerInput.OnFoot.Movement.ReadValue<Vector2>();
        playerMotor.processMovement(input);
    }
    private void OnEnable()
    {
        playerInput.OnFoot.Enable();
    }
    private void OnDisable()
    {
        playerInput.OnFoot.Disable();
    }
}

So he uses the event delegate system for OnFoot.jump, but he reads the value directly for OnFoot.movement...

#

couldn't he instead read OnFoot.Jump directly?

#

like this ```cs
void Awake()
{
playerInput = new PlayerInput();
playerMotor = GetComponent<PlayerMotor>();
}

void FixedUpdate()
{
    Vector2 input = playerInput.OnFoot.Movement.ReadValue<Vector2>();
    bool jump = playerInput.OnFoot.Jump.triggered;
    playerMotor.processMovement(input);
    if (jump)
    {
        playerMotor.Jump();
    }
}```
quartz folio
swift falcon
# quartz folio If you're following a tutorial from Brackeys then that's your problem. Find some...

The first video in a series where we are creating a First Person game!
In this video we look at setting up our characters movement.

I've setup a Discord!!! and I would love to have you help me start up a friendly community where we can all help each other grow as game developers!

Discord invite link:
https://discord.gg/xgKpxhEyzZ
Can't wait t...

โ–ถ Play video
#

it's this guy

quartz folio
#

It does seem like bad code, but as long as you're learning how to write code in Unity then it's doing its job ๐Ÿคท it's hard to find youtubers who are going for quality over quantity. Or at least, they have a lot of other work like editing and an inability to backtrack that makes quality difficult.

swift falcon
fluid lily
fluid lily
west sparrow
#

Yeah, it's a bit of a make work project.

#

I don't recommend using URP unless you have a usecase for it

fluid lily
#

Unity can be a bubble of weird practices. And studying other C# industries will be the biggest eye opener.

fluid lily
quartz folio
#

If it's just the environment settings, then I believe that's the same as the default pipeline, RenderSettings.fogColor

sage latch
#

Somehow I feel like my method is just stopping halfway through. I get the first log, but not the second one and it doesn't seem to return control to the caller either. It only happens after I reload the scene, maybe that has something to do with it?

    public void Initialize(GameSettings gameSettings, MapData map, IEnumerable<PlayerData> players) {
        Settings = gameSettings;
        
        Debug.Log("Loading map", this); // I get this log
        MapManager.Instance.LoadMap(map);
        
        Debug.Log("Creating players", this); // But not this one
        foreach (var playerData in players) {
            PlayerManager.CreatePlayer(playerData.Id, playerData.RobotData, playerData.Name);
        }
    }
#

There's no while loops or async functions involved

fluid lily
quartz folio
sage latch
quartz folio
#

I don't see why that would happen. Have you tried following it through with the debugger?

sage latch
#

I'll see

#

Everything goes through

#

But no logs show up :/

fluid lily
#

The scene is using URP as the renderer, my textures are URP textuers, but my fog is default render settings.

sage latch
#

Also in the Game view it hasn't switched scenes yet, is that a problem? I'm calling this from OnNetworkSpawn on an in-scene placed NetworkBehaviour

somber nacelle
#

not a code question, but it looks like the rect is reversed

ancient rock
#

I mean, either you're targeting low-end devices (what URP is made for), of you're targeting high-end devices (what HDRP is made for).

fluid lily
ancient rock
#

User Experience of URP is bad?

#

Not sure what UX is referring to here.

#

Because I've been using URP for my game and it seems fine to me.

sage latch
#

I guess the scene loading caused it

#

Nevermind, it broke again

arctic marsh
#

Morning everyone, hope you are having a good day and hope it treats you well.

So I have a bit of an issue, I did post this last night in #๐Ÿ’ปโ”ƒcode-beginner but its been a solid amount of time since then and I feel this goes beyond starting level Unity, so here goes. Slight AR rubbish involved here too.

I am trying to get a pickup system working, like an inventory system. I decided to do the following.

a) Create a GameObject, titled Inventory, which has a list that can house ScriptableObjects.

b) The ScriptableObjects house the pickup data, such as type, effect value ect.

c) The pickup, has a component that houses all the possible items that item can add to the inventory.

The issue here, is when I try to Trace from my AR camera position, the Pickup tag objects are successfully detected, but I can't seem to successfully return any data from it. GetComponent or otherwise.

Here is the script I'm having problems with, specifically lines 58 through 100, I can definitely take a look at the rest of the setup if needed. NOTE: The debug messages are UI text, the game successfully detects what object was hit if its of the type "Pickup", it returns a standard "Hit" if nothing was hit. Line 93 doesn't overwrite the text to anything and therein lies my issue.

https://srcshare.io/641eb515ca97b4ee16cec26b

Many thanks in advance. Please let me know if there are any more details you need. I will get myself some breakfast ๐Ÿ‘

#

(Debug.Log is not possible as I have to test the project on my phone. Using Unity Remote will not render my camera as a result.)

cosmic rain
#

Not just logs, you could even connect a debugger and step through the code with breakpoints.

arctic marsh
#

Hm, okay, interesting.

#

I've at least gotten it down to that area of line 58-100

#

Quite frankly I never want to do AR dev after this, ever again.

cosmic rain
#

You can see the logs by using logcat. Either as a part of android studio, separate app or a unity plugin. You could also just connect the editor console to the build.
To connect the debugger, you need a development build.

arctic marsh
#

Okay, thats useful. Thank you, I'll give that a proper look.

Do you have any possible ideas as to why Line 93 doesn't return anything?

lucid valley
#

put in a try catch if you want to double check, can then log the exception to the touchDebug.text

arctic marsh
#

touchDebug.text = hit.collider.gameObject.name; works, after that point, I'm facing issues.

#

So we are definitely at least getting the object, just not its data.

arctic marsh
cosmic rain
#

Connect the console or see the logcat for wether there are errors thrown.

cosmic rain
#

Don't do that.

arctic marsh
#

Man, really wish I didn't have to set up more apps for a small assignment, but okay.

cosmic rain
#

It doesn't have to be an app. Use the logcat package for unity. That's the most convenient way.

#

And if that's too much for you, just connect your editor to the build and you'll see the logs in the console.

arctic marsh
#

When I do build and run, I need to use the development option then? I'll try logcat first.

cosmic rain
arctic marsh
#

Ok, lets see if this reveals anything, probably not though, GetComponent really annoys me at times.

sick minnow
#

Hi!

I am trying to add steam achivements to my Unity game (Don't know if this is the right place to ask, but couldn't find any other place - sorry)

I tried making this basic script: https://pastebin.com/3pMfzWvX

but I get the erros that SteamUserStats does not contain a definition for Get and SetAchivement

lucid valley
#

Steamworks.SteamUserStats

#

line 27 and 28 are just SteamUserStats

#

so try Steamworks.SteamUserStats there instead

#

uh, actually you have the using statement

#

humm, strange

sick minnow
#

yeah, I tried that now, but I get the same errors ๐Ÿค”

lucid valley
#

oh, lol spelling error

#

achievement is spelt wrong

#

forgot the first e

arctic marsh
#

Okay, so theres an error as far as the game trying to add an item to a list is concerned. How do I properly add stuff to one during runtime?

sick minnow
#

oh, lol

#

lol, that fixed it ๐Ÿ˜†

#

thanks @lucid valley ๐Ÿ™‚

arctic marsh
#

That would explain a lot.

lucid valley
#

yup

arctic marsh
#

If this works I will be happy and also kinda seething.

#

my fking god. Thank you @lucid valley

ruby fulcrum
#

how do i get the time elapsed since the previous while loop iteration in a coroutine

quartz folio
ruby fulcrum
#

so thats why its not doing it right i forgot to put yield

#

ok ty

#

so basically

#

if i put yield return null in a while loop coroutine

#

it will yield the coroutine until the next frame begins?

quartz folio
#

yes

ruby fulcrum
#

i see

ruby trellis
#

Im trying to make a lock on UI for my space game like in the game outer wilds where it shows you the relative velocity of a planet relative towards the player but the code I've got right now only works when looking at the planet at a specific angle because the speed axis are global and not relative towards the player. Is there a way to fix that? The image is an example of what it looks like in outer wilds

    void Start()
    {
        lastPosition = targetTransform.position;
    }

    void FixedUpdate()
    {        
        Vector3 currentPosition = sunTransform.InverseTransformPoint(playerTransform.position);
        Vector3 targetPosition = sunTransform.InverseTransformPoint(targetTransform.position);

        Vector3 dist = currentPosition - targetPosition;

        if (lastPosition == Vector3.zero)
            lastPosition = dist;

        Vector3 diff = dist - lastPosition;
        Vector3 speed = diff / Time.deltaTime * 10000;
        lastPosition = dist;

        Debug.Log(currentPosition);

        // Stream the value of relative velocity to a UI text object
        velocityText.text = speed.z.ToString("0.000");


        Vector3 targetScreenPosition = Camera.main.WorldToScreenPoint(targetTransform.position);
        velocityText.rectTransform.position = new Vector3(targetScreenPosition.x, targetScreenPosition.y, 0);
        LockOuter.rectTransform.localPosition = new Vector3(speed.x, speed.y, 0);

        if (targetScreenPosition.z <= 0)
        {
            velocityText.gameObject.SetActive(false);
        }
        else
        {
            velocityText.gameObject.SetActive(true);
        }


        
    }
worthy yoke
#

Hello, how should i handle i/o threads in unity? Create .NET thread or event native thread from winapi?

open lake
#

bois

#

ladies and gentlemen

#

how do I compress images permanently

#

not just like a build thing

tepid river
#

Subtract ship velocity from planet velocity => get relativevelocity. Then use dot product to cast it onto axis of choice

hazy shell
#

hey everyone, does anybody know why I keep getting this error or how to get rid of it?

pine bronze
#

hey guys, this isnt really that big of an issue but it really annoys me, whenever i jump, you can see that i go to the left/right slightly. idk if this can be fixed but it annoys me very much. here is my code:

private void Jump(InputAction.CallbackContext ctx)
    {
        if (grounded && canJump)
        {
            canJump = false;

            rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.y);

            rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);

            Invoke(nameof(ResetJump), jumpCooldown);
        }
    }
quartz folio
hazy shell
dense spear
#

hey buddy!! I tried it and it works like a charm!! Thanks for that I have a small issue with this... so I have made the corners and set it as a child to the plane (just for debugging purposes) and I noticed that as I increase the size of the plane, the size of the frustum increases upto an extent and after a certain point, it starts rotating as well... is there anything to stop that? something like this in the video...

languid quarry
#

any ideas on how to launch a separate .exe file from a game? my goal is to make a game launcher, essentially.

#

here's what I have so far

#

however it throws a "mono io layer" error, and after digging around the forums for the past 2 hours ive yet to find a fix for that.

simple egret
#

Might not fix your issue, but just for safety you should be using Path.Combine() to join paths, instead of using string concatenation with +

#

You might be passing a path that looks like this right now path/to//file.txt and that's definitely invalid

#

Say if dataPath ends with a slash

languid quarry
#

i've never worked with something like that. could you please share the syntax on how I'd use Path.Combine?

simple egret
#

string good = Path.Combine(path1, path2)

languid quarry
#

thanks

simple egret
#

(you can pass more than two arguments if needed)

languid quarry
#

got it working now. it turns out the issue was me using a shortcut file to navigate to the correct executable inside another folder

#

combining the path instead of using the shortcut works. turns out they break after building or whatever

ruby trellis
sick minnow
tepid charm
#

just coded a pretty complicated algorithm for determining which soldiers in an army are in combat and who they are fighting, and it actually worked first try

#

crazy

languid quarry
#

im proud of you shrek

wary wagon
#

Im making a property editor for the inspector, for dictionaries. I want for each value of the dictionary, use the default property editor to render them . How can i do that ?

leaden ice
#

Or just make a list of key value structs

wary wagon
#

You have one to recommand ?

#

I adopted one long ago but it has no editors ;D

leaden ice
#

I would just be googling it and taking the first result

wary wagon
#

oh wait im dumb i didnt import the ditor at the time because i didnt know what it was

empty gust
#

Hey guys, so i have poroblem when build my game in webgl. It wont call my API requsts, but in unity editor mode it works perfectly.
Any ideas on what could be? Can it be something in Player Settings when try to build game?

west sparrow
empty gust
empty gust
tepid river
ruby trellis
tepid river
#

but why would that stop you from using rigidbody phyisc?

#

cant you just attach the terrain to a child object?

ruby trellis
#

Does that work

tepid river
#

not sure, i never had the issue. but i would assume so

#

its just that "my collider is not convex so i have to build my own phsx simulation" doesnt sound right to me ๐Ÿ˜„

ruby trellis
#

Well sadly that is sometimes jow unity is

#

One limitation so you have to do ever,thing from scratch

elfin tree
#

Hi, I'm trying to make it so moving the mouse around the screen slightly moves the camera towards the cursor, but with bounds, or could be just one value uniform across all directions screen. I'm not quite sure how to search for this but I'm sure this has been done before online, how can I go about this or search for this, thanks!

shut elm
#

Hey, I have got an question, when I do this, "y" never reaches 50 (because of y < noiseTexHeight, which is how it should work).
for (int y = 0; y < noiseTexHeight; y++) { float yCoord = yOrg + y / heightscale; int ytimeswidth = y * noiseTexWidth; if (ytimeswidth == 2500) { Debug.Log($"y{y},wi{noiseTexWidth}"); } for (int x = 0; x < noiseTexWidth; x++) { float xCoord = xOrg + x / widthscale; float sample = Mathf.PerlinNoise(xCoord, yCoord) * 255; byte samplebyte = (byte)sample; pix[ytimeswidth + x] = new Color32(samplebyte, samplebyte, samplebyte, 1); } }

But when I execute that code async "y" somehow reaches 50, why is that? There is in my opinion nothing that should affect y in that lines...

Task[] tasks = new Task[noiseTexHeight]; for (int y = 0; y < noiseTexHeight; y++) { tasks[y] = Task.Run(delegate { float yCoord = yOrg + y / heightscale; int ytimeswidth = y * noiseTexWidth; Task[] innertasks = new Task[noiseTexWidth]; for (int x = 0; x < noiseTexWidth; x++) { innertasks[x] = Task.Run(delegate { float xCoord = xOrg + x / widthscale; float sample = Mathf.PerlinNoise(xCoord, yCoord) * 255; byte samplebyte = (byte)sample; pix[ytimeswidth + x] = new Color32(samplebyte, samplebyte, samplebyte, 1); }); } Task.WaitAll(innertasks); }); } Task.WaitAll(tasks);

leaden ice
#

this loop is going to happily run: for (int y = 0; y < noiseTexHeight; y++)
while the other threads are trying to read it:
float yCoord = yOrg + y / heightscale;

#

I think you'd want to make a copy for each of your delegates

#

like int yCopy = y; then use that yCopy in the delegate

#

otherwise they're all readying that same y variable

teal silo
#

A question about simulating FOVs:

For class, my team is creating a 2D stealth platformer (not top down). I'm in charge of enemyAI, which includes movement and detection. So far, I followed Sebastian Lague's enemy FOV tutorial and it has served as a pretty good base. A very important part of our gameplay is that we want our character to be able to crouch behind objects in order to not be seen by the enemy. I have achieved this by having two capsule colliders of different heights and activating and deactivating them with button inputs (this part works great).

At first, I could not get Lague's method to work for our idea because the raycast he uses to check if there are obstacles in the way was drawn from the center of the enemies view to the center of the player's collider, and would inevitably collide with an obstacle if the center of the player's collider was even a bit lower than the object, while the rest of the collider was theoretically visible to the enemy. I "fixed" this issue by putting a circle collider on the top of the players head. This worked okay, except for the fact that if the player climbed on top of an object and said circle collider was outside of the enemies FOV, then the enemy would stop detecting the player, regardless of the body being inside the FOV.

My question is: would there be a way to cast various rays within the angle of the enemies FOV to detect the player collider regardless of if the center is being obstructed? Or, in the case of this method being highly inefficient, is there a better way to do this? I'm kinda lost and I want to get this done and working before starting with the enemy AI since this is a very important part of the gameplay.

Here is a link of the tutorial I am referencing, it should take you to the part where the code is complete https://youtu.be/rQG9aUWarwE?list=PLFt_AvWsXl0dohbtVgHDNmgZV_UY7xZv7&t=1213. If you would like to see my code, I can also include a snippet of that.

In this miniseries (2 episodes) we create a system to detect which targets are in our unit's field of view. This is useful for stealth games and the like.

Source code + starting file:
https://github.com/SebLague/Field-of-View

Support the creation of more tutorials:
https://www.patreon.com/SebastianLague
https://www.paypal.me/SebastianLague

โ–ถ Play video
tepid river
shut elm
tepid river
#

if your player has a simple geometry, sampling points inside it is even easier.

teal silo
tepid river
#

doesnt matter i guess, if it intersects, it intersects

shut elm
leaden ice
#

although it's also possible your code is flawed in some way

#

I didn't read it too closely

teal silo
tepid river
#

hm something like Random.sampleUnitSphere and then multiply with the bounding box dimensions i guess
add a * 0.75 to scale the points to 75% so its not just inside the BBX but most likely also inside the geometry?

#

you could also have a couple fixed points so its easier to debug

teal silo
tepid river
teal silo
#

And I'll read up on the sampleUnitSphere since I hadn't heard of it before

tepid river
#

its a static method of unity Random iirc

#

or vector3, one of them

teal silo
#

Thanks for the suggestions and the clarifying drawing, I'll see if these methods solve my problem :)

tepid river
#

its a common problem. in early Arma 3, you could hide behind street signs, bc it would hide your face from the enemy

teal silo
#

Hah! I didn't know that, and I've played Arma3 quite a bit. It's good to know that it's not just me being a beginner

tepid river
#

flipside is, now it can detect you when it sees like your elbow through the foliage and laser-nuke you through the bush

#

๐Ÿคทโ€โ™‚๏ธ

#

i guess an improved approach might be randomly sampling rays and counting up how many return "can see".
and then have a threshold after which the AI descides "yeah ive seen like 50 of 100 samples, im pretty sure i can see the player"
edit "ive seen this elbow now 50 times, time to nuke the playyer" lol

teal silo
#

Thats another good idea. What I had thought is to cast multiple rays from the center of the enemies view to different points along the external radius of the FOV, all contained within the angle of the FOV. But I have a feeling I'm going to need math for that and I suck at math, so we'll see.

tepid river
#

i wouldnt randomly cast to somewhere in FOV. instead, directly cast onto the interesting objects and test if they are visible

#

the probablity to detect something if you just cast to a single ray fixed to your enemies rotation are very slim.

#

it might make sense for movement tho

teal silo
tepid river
#

if your game has few enemies/players, you can probably go a bit crazy on detection performance.

teal silo
cedar egret
#

how would I store unique data on each tile using tilemaps?

mystic ferry
#

I believe you would have each tile represented with a scriptable object

#

could be wrong though

cedar egret
#

GameObject?

cedar egret
#

alright

#

But how would that work Tilemaps?

#

I assign that object to

#

each tilebase?

mystic ferry
#

not sure, I havenโ€™t worked with something like that before

#

sorry

cedar egret
#

ah np

mystic ferry
#

I think codemonkey has a heatmap video that might be of some use

upper pond
#

how do i calcualte the angle a 2D gameObject is moving in? ive been searching the internet for about an hour with no avail

cedar egret
#

wdym calculate the angle

upper pond
#

say a Gameobject moved directly from left to right, the angle that it is moving at would be 90 degrees, or bottom left to top right, the angle would be 45 degrees

cedar egret
#

if u have an input

#

like

upper pond
#

wasd?

cedar egret
#
Vector2 input = new Vector2(horizontalInput, verticalInput);
float angle = Mathf.Atan2(input.y, input.x)
#

i think

mystic ferry
# upper pond wasd?

angle on the transform is a local space angle, but thereโ€™s a readonly worldspace angle on the transform called transform.lossyScale

cedar egret
#

other way

upper pond
#

take your time

mystic ferry
#

thereโ€™s also Vector3.Angle for between two objects

upper pond
cedar egret
#

atan2 should work

mystic ferry
#

whatโ€™s wrong with MoveToward()?

#

Then thereโ€™s Vector3.Lookat or something like that to line up normals

cedar egret
#

@upper pond did u try it?

upper pond
upper pond
jagged laurel
harsh pasture
#

Hello, I've been looking into the Strange IoC package. It's fairly old and hasn't seen any updates in awhile. Is it still relevant in Unity dev today?

ashen yoke
#

there is extenject and other maintained libraries

upper pond
thorny onyx
#
    {
        for(int i = 10; i > 0; i--)
        {
            yield return new WaitForSeconds(1f);
            speedCountdown.text = i.ToString();
            if(i == 7)
            {
                DefaultSpeed = 1;
            }
        }
        
    }```
#

how can i fit a loop into a corountine like this

#

or do i just have to manually type it out

#

maybe i can declare i outside

ashen yoke
#

dont understand what youre asking, the code is valid

elfin tree
#

I'd like to compare two Quaternions after using Slerp to dermine if the rotation is finished, with a margin of error, how? RESOLVED

steep herald
#

Is there a way to manually iterate over a shader variants collection?

plucky karma
#

I wonder - has anyone managed to invoke Rustc lib inside Unity, and any pro/con doing this other than malloc for CAPI calls?

tepid charm
#

any idea why a quintuple nested loop would cause 170ms garbage collector frame spikes?

dim spindle
#

Could you please post the code mentioned?

#

Also have you for sure narrowed it down to this loop

#

Btw the reason you should post the code is because there are a LOT of reasons why that could happen

tepid charm
# plucky karma wait, a _quintuple loop?_
        for (int i = 0; i < sideTiles; i++)
        {
            for (int j = 0; j < sideTiles; j++) 
            { 

                foreach (Soldier soldier in buckets[i, j]) 
                {
                    
                    for (int x = -2; x < 2; x++)
                    {
                        if (i + x < 0 || i + x >= sideTiles)
                            break;
                        for (int y = -2; y < 2; y++)
                        {
                            if (j + y < 0 || j + y >= sideTiles)
                                break;
                            
                            closeSoldiers.AddRange(buckets[i + x, j + y]);
                  
                            boxPositions.Add(new Vector2((i - x) * tileSize - gridSize / 2, (j - y) * tileSize - gridSize / 2));
                        
                        }
                    }
                    closeSoldiers.OrderBy(x => (x.transform.position - soldier.transform.position).sqrMagnitude).ToList();
                    

                    foreach (Soldier other in closeSoldiers)
                    {
                        if (other.unit.team != soldier.unit.team)
                        {
                            soldier.combatTarget = other;
                            other.combatTarget = soldier;
                            other.isFighting = true;
                            soldier.isFighting = true;
                            break;
                        }
                    }
                }
            }
        }```
plucky karma
#

foreach is probably what's generating garbage collection...

tepid charm
#

yeah probably

plucky karma
#

and good god man.. Why so many loops?

tepid charm
#

I'll swap it out, 1 sec

tepid charm
vagrant blade
#

Possibly that Linq line

tepid charm
plucky karma
#

Yup, Linq will most definitely allocate garbage!

vagrant blade
#

Now you can be bothered to!

plucky karma
#

Why do you need them in order? I don't see a reason why?

tepid charm
#

to find the closest

plucky karma
#

Why?

vagrant blade
#

Picking targets likely

tepid charm
#

because each soldier finds the closest enemy as a target

#

yeah

plucky karma
#

Would consider relying on physics cast instead of checking distance?

tepid charm
#

for some context, this is a prototype I started working on yesterday, it's a total war-esque game and this is my 6th attempt at making one

#

I always run into a brick wall of performance issues

#

so trust me, I've tried most things I could think of lol

somber nacelle
#

well checking distance against every single enemy is going to be much less performant than a spatial query like an overlap box and just getting the closest object from that

plucky karma
#

There's always some things you can try, but multiple for loop is never one of them. It's prone to have problems and can bottomneck your performance in unity at runtime.

vagrant blade
#

There must be something like GDC talks on the subject

plucky karma
#

In fact, all of this is on main thread, talk about halting your program for a sec here.

vagrant blade
#

Dots would be a good usecase here yes

tepid charm
#

I've tried learning DOTS twice

#

but I can never figure it out

somber nacelle
tepid charm
cedar egret
somber nacelle
tepid charm
#

anyway keep in mind this is the 1st iteration code, I haven't really optimized it yet, just trying to work through the biggest issues first

#

so I'll try to find an alternative to the Linq and swap out the foreach loops

blissful whale
#

Is there a command like this but will not work when it is held

blissful whale
#

yep that one, thanks

upper pond
upper pond
tepid charm
plucky karma
#

C# isn't easy to learn guys... It's ok, but you're learning. That's the important part!

#

Not as bad as writing C, but hey, you get to deal with garbage collector ๐Ÿ˜„

thorny onyx
#

anyone know what this means

somber nacelle
#

you have code that isn't inside of a class

thorny onyx
#

yeah thats what i thought

#

nothing is outside tho

#

nvm

#

sorry

#

i had brackets outside

#

thanks

crystal creek
#

does anyone here understand the discord game sdk? ive gotten most of it working but when i send a game invite for my game in discord i get this

crystal creek
buoyant mural
#

oh

crystal creek
#

i do have permissions to send it

#

i can send it for other games

buoyant mural
#

Your application might not have permissions

#

Check the Discord Application

#

In Developer portal

crystal creek
#

where do you give it permissions???

buoyant mural
#

In general information I think let me see real quick

crystal creek
#

i dont see anything

buoyant mural
#

Ok wait I'll check rn

#

I think you need a Authorization link

#

in Oauth2

crystal creek
#

uh... now im confused what to do because i need a redirect url

buoyant mural
#

Ah can I see your invite code?

crystal creek
#

nvm hang on

buoyant mural
#

I think I used my IP

#

before I forgot honestly

#

@crystal creek Use this
http://127.0.0.1

crystal creek
buoyant mural
#

rpc

#

This should allow your application to access your discord client if I'm correct

crystal creek
#

hm

buoyant mural
#

Also In OAuth2 add in redirects the same link

crystal creek
#

yeah still no

#

it just sent me to this in my browser

buoyant mural
#

Show me your invite code

#

as I said before

#

it must be a problem from your code itself

crystal creek
buoyant mural
#

The code for the invite

#

like

crystal creek
#

also prob better to move this to dms

buoyant mural
#

ok

#

yeah

severe coral
#

How would I cache reflection results (through the editor ) to quickly be able to access a field from any instance of a class at runtime?

#

Also could I use TypeCache for this, and if so how fast would it be?

candid kiln
#

how can i play a sound for each particle's birth in my particle system?

plucky karma
severe coral
ember coral
#
if(isGrounded) {
    elapsedInAir = 0;
    hasJumped = false;
} else {
    elapsedInAir += Time.deltaTime;
}

if(Input.GetKeyDown(KeyCode.Space)) {
    jumpBufferCounter = jumpBuffer;
} else {
    jumpBufferCounter -= Time.deltaTime;
}

if(isGrounded) {
    
    if(jumpBufferCounter > 0) {
        rb.velocity = new Vector2(rb.velocity.x,jumpForce);
    }
} else if (elapsedInAir < coyoteTime && !hasJumped) {
    if(Input.GetKeyDown(KeyCode.Space) ) {
        rb.velocity = new Vector2(rb.velocity.x,jumpForce);
    }
}

if(Input.GetKeyUp(KeyCode.Space) && rb.velocity.y > 0) {
    hasJumped = true;
    rb.velocity = new Vector2(rb.velocity.x,rb.velocity.y / 2);
}```
#

I have this code for jumping the problem is that has coyote time and input buffering the only problem is that you also jump as high as you leave pressed and that dosnt work quite right with this input buffer

ember coral
#

I want to take how long you pressed and after that time passed stop jumping

slow grove
#

Hey guys, I'm building a large game that requires moving/rotating the world around the player, only issue is that the illusion of movement is broken since the skybox doesn't rotate. What would be a possible solution? I was thinking maybe making a fake skybox and rotating that, or possibly something involving one camera to render the scene and one to render the skybox maybe?

eternal geyser
#

guys i got a big problem

#

i am really hard struggling with a code

sleek heath
ember coral
#

I know

eternal geyser
#
public static void Main()
{
      public void Start()
    {
        HouseKey = GameObject.Find("HouseKey");
    }

    public void Update()
    {
        Debug.Log(HouseKey);
    }

}
ember coral
#

But somehow for me it maintains my code cleaner

eternal geyser
#

the object is deactivated

eternal geyser
#

its like impossible

hot yacht
eternal geyser
#

even if i put it in update the search for gameobject the same error occures that the following gameobject does not exist or is not assigned

#

and i know why, its because its deactivated, it needs to be deactivated because if want to use an system where i can just turn on and deactivate the gameobject

#

I am for the first time at an point where i have no conclusion what to do

#

i dont know if i need to use instantiate, maybe thats better

buoyant mural
#

Hello I'm having a problem with this, yaw becomes -0.002f for a frame then 0 the other frame, why is this happening?

        private IEnumerator Rotate(bool negative)
        {
            if (negative)
            {
                yaw -= 0.002f;
                yield return new WaitForSeconds(1f);
                yaw = 0f;
                yield return new WaitForSeconds(1f);
            }
            else
            {
                yaw += 0.002f;
                yield return new WaitForSeconds(1f);
                yaw = 0f;
                yield return new WaitForSeconds(1f);
            }
            yield return null;
        }```
#

It's not waiting for 1 second

#

(I have a feeling I'm using this completely wrong)

rain minnow
buoyant mural
#

No

eternal geyser
buoyant mural
#

Well I want decrease yaw for a second then put it back to 0 then wait again and repeat

#

But I'm not very good with coroutines

steep saddle
#

Where are crash logs for a build? Not the editor

severe coral
#

Hey honestly, all of this reflection stuff seems like a pain in the butt, could I just generate a script through code that could then be compiled and used whenever I need?

slow grove
solar current
#

i need help

#

please some body talk

vagrant blade
ruby trellis
#

I need to make a system for selecting an object in my scene when you look right at it and press left mouse. To find the selected object should I do a Raycast straight from the camera and just see what it hits? Because there might be a better option that I don't know of especially since the object could me thousands of meters away in my game

vagrant blade
#

Raycasts have a length option