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)?
#archived-code-general
1 messages ยท Page 65 of 1
What does the AtlasTypes.SmootgMoves do? You need to know that if you want to replace it.
Also, deprecated doesn't necessarily mean that you can't use it.
From what I could find, it seems SmoothMoves comes with it's own atlas builder, that can create sprite atlases for the user and allow the user to manually edit sprite pivot, my best guess is that it references those types of files.
If your friend send the script why not tell him to send it's plugin too
But I think a better place to ask is #๐โanimation
worked with plugin
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?
And is there any way I could move them at the same time in C#
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
They're all seprate
That's not good use:
I'll try this
But if you want them to move at the exact frame then make an empty GameObject
it's easier
I've tried this already but I can't figure out how to move them
ok
foreach(GameObject objectToMove in objects)
{
objectToMove.Move();
}```
I'll give that a go
you could try using this but I highly suggest the empty GameObject method
The foreach method is very expensive
Oh ok
Just do this and move StuffToMove
Hey
i'm trying to use NavMesh.CalculatePath, but it returns false. i have a basic flat navmesh
Try moving your start position onto the navmesh with NavMesh.SamplePosition before calculating the path
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?
in Truck Game
im trying to connect trailer with my truck
so i use configurable joint but i have few issues...
- my trailer is floating like balloon in starting lol (it get on ground when i move truck)
- my wheel colider bounce when it touch with other object
- my trailer just keep moving left and right the limit i have provided
Any Suggestions or Helpful material ? Anyone can suggest
it also returns false. does it do something like a sphere check?
It tries to move the position to the navmesh inside the radius you give it
https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html
@rotund burrow How did you use it? Maybe you did something wrong
NavMeshHit hit;
if (NavMesh.SamplePosition(transform.position, out hit, 100, groundMask))
yes
You need a NavMesh area mask
If you want every area then use NavMesh.AllAreas
Or GetAreaFromName if you have specific areas
okay it works now, thanks
@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);```
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 ๐
I didnt give you any code, I told you the steps to do it, and you did it wrong.
I meant that
yeah
ok well um what did I do wrong here?
Why dont you use Vector3's like I suggested
How do you expect this to workcs Vector2 direction = destination.position - transform.position;
Those are Vector3's and you assign it to Vector2
oh yeah
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
Ok turns out I tried using Vector3 wrong today my bad, now it's working when I did it right
Read^
It worked 
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.
I didn't ask design choice advice...
I asked how do I get similar axis from touch input.
As in the methods?
the boxcollider is not meant to be used in UI scope. You first gotta make sure you got an EventSystem in your scene and also a graphics raycaster on your UI Canvas
As in, what's the equivalent to GetAxis() for touch.
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?
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);
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
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
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
as we are in this scope, could you imagine a good way of adding a coroutine to a monobehaviour like extending every mono with a static animationroutine that can be updated? Or would you just create an inheritance of that mono adding all the functionality?
So right now I am doing this https://hatebin.com/ckbhlsmqcf
Just testing, again, ignore the position / scale naming issue ๐
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
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! ๐
Hello, how do you reference this question generator into the text component, im still not getting it, tq
Can you give a bit more detail what you mean?
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
You never call an update on the questiontext cause you never call the int method above
yay it works tq! .
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);
Is routineof type IEnumerator?
Yes, it is
I'm not sure how the StopCoroutine(IEnumerator) overload is supposed to work
But I know that StopCoroutine(Coroutine) works
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
What if you try cs StopCoroutine(coroutineReference); coroutineReference = StartCoroutine(...);
coroutineReference would be of type Coroutine in your case?
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
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.
I think that is the three options you have, String, IENumerator or a Coroutine itself?
Yeah but the last sentence says to stop it with Coroutine
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
I always stopped coroutines with a Coroutine reference so thats the only one I know to work for a fact
So that works in your case?
Stopping always worked, let me refactor to start not the inumerator but set it to a coroutine reference
Argh... ๐ still not working
What is iENumType? What if you store the coroutine in the mono?
Also how are you starting it currently
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.
Ah so the problem is with passing around the IEnumerator?
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
yeah it was the graphics raycaster thanks a lot
Or use the string overload? 
Then I could not pass any values in ๐
https://hatebin.com/eesjuajlyq if you are interested, this is working now ๐
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.
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;
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
My code if anybody is willing to help: https://hatebin.com/vlawucfoer
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?
So you want the coroutine to run again every time you start it in OnTriggerEnter?
Or just one coroutine that loops?
The while loop is for repeating code inside one coroutine
[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
Yes, I want it to run every time the bullet collides with the trigger/enemy.
The text is almost always in a child object of the button
Your current code should work, just without the while loop
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
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.
Which bool is that?
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.
Hmm. Are you sure that some other script isnt changing zombieKill?
The issue doesnt seem to be in the code you showed
I created a TMPro text and added button to it. So it's not a child
The only other script using it is my GameManager script. And it's just a simple update function. if zombieKill is true, add points.
You need to explain your issue then
what's going wrong
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"
your script is not on the same GameObject as a TextMeshProUGUI component
In my mind I'm referancing the object by calling gameObject
gameObject gives you the GameObject your script is attached to.
And you removed the while loop, right?
Can't really speculate further without seeing more code
Also where exactly are you logging the value of zombieKill?
It's attached to the same object
Show the inspector?
What about string nameItself = gameObject.GetComponent<TMP_Text>().text;?
can you show the full error messge (with the line number) and the full Select Num script?
`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)
tried that still getting the same error
Please format your !code properly
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.
Here is the update function in the GameManager script: https://hatebin.com/obzzhhemov
Your error is on this line:
GameControl.clickCount += 1;
you need to pay attention to your error message
it's because you haven't assigned GameControl
You didn't assign GameControl if you check your inspector...
clearly visible in your screenshot that it is not assigned
Looks ok, are you sure you dont have multiple GameManagers in the scene?
Here is the KillsPlayerOnTouch script: https://hatebin.com/jtpehizfwv
Let me check
GameControl is another script. I tried to update a method that's in GameControl
I know what you're trying to do
Type t:gamemanager in the scene's hierarchy search bar
To search by type
We've just showed you what your problem is @obsidian eagle and how to fix it. Good luck.
Yeah only one, attached to the gamemanager object
Alright, thanks...
But you didn't assign it in the inspector, so there is no reference to call.
how do I assign a script in the inspector?
drag and drop
no it's not an object it's a sciprt
you're wrong
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
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
did you assign the thing?
yes
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.
Screenshot your inspector, please
Alright I found the problem. I was clicking on the one that I didn't attached the game object to.
Thanks a lot guys
Thank you anyway. I'm gonna reach out to both my professor and the creators of this Unity Asset we have to use for our project to see if they can help solve the issue or if I'm just not seeing something
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 ๐
Hello, can anyone help me, how to reference this script into a button?
by adding it to the button's event list
assuming you want that script to run every time you press a button
Random.Range has an int version btw
But how do I make it change the text of the button?
is it somthing like this?
answerText_1.GetComponentInChildren<Text>().text = answerChoices.ToString();
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.
Im trying to make a simple math game and cant figure how to get button to change
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
the hierarchy is a tree, and FindObjectOfType uses DFS I believe
that said, FindObjectOfType is one of the worst, least performant ways to fill a dependency
gotta love chat gpt explanations. a google search led to looking at different links.
FindObjectOfType does no follow any guaranteed hierarchy search order and may change from platform to platform and in different Unity versions
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
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
I cant really cache it in my manager since the tutorials happen even after scene change
do your managers not persist through scenes?
they do but i'm using a utility DDOL class to spawn my popup prefab which finds the canvas in whatever scene its in
not really sure I'm following how this precludes a typical singleton setup
when the scene changes..the canvas does also.. So you can't cache the object of my canvas once its found the first time
void Awake() {
instance = this;
}```
that's all you need, no?
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
right and I just showed you what to put on the canvas in order to find it
you could also just make the canvas DDOL
especially if it's a popup - it should probably have its own canvas
If you have a manager that is DDOL just make a variable on it and reference the canvas gameObject . . .
Or does the canvas not persist through scenes?
It doesn't
This would work, I guess I would still need reference to the primary canvas to get my custom scaling values to apply to the popup's canvas though. This is a mobile app, So I have some custom values for screen referencing depending on device.
Then as Praetor suggested, make a canvas that persists for pop-ups . . .
Ill try that and see what happens
You should have separate canvases for different UI where necessary to avoid redrawing canvases . . .
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.
Using a custom inspector or property drawer.
Gah. I was afraid that might be the only way. ๐
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?
make a "proxy" object as part of your normal object prefab
with all the stuff set up on it
and show it in the right place/right time when necessary
otherwise hide it
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??
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
for (int i = 0; i < 5; i++)
{
var tmpStar = starsList[i];
var bg = i < numStars ? starsFull : starsEmpty;
tmpStar.style.backgroundImage = new StyleBackground(bg);
}
Ah nvm fixed
could you explain the var bg line for me pls ๐
does any one know how to make my character not float when he goes off the map?
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
pretty much your choice is tuple or struct/class
Is GetComponent considered FindObjectOfType during runtime?
I mean a struct/class is just an overkill for this purpose, tuples seem more convenient and natural
makes sense
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๐
It's basically the same thing as a tuple, the main difference is a tuple is temporary if only used for the method or seldom. If you need it in multiple places then a struct is more preferable . . .
Two or three is fine for a struct. A struct shouldn't be more than a handful of fields anyway . . .
yeah the sole purpose for me is to return a (JobStruct, JobHandle) pair from a method, that's it
Nope, not the same thing . . .
How can I lock the value of a variable after changing it once?
So that it can't be changed again
Use a bool variable to track if it's been changed already
There are many variables
Which I have to control individually
Bool approach is not appropriate
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
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
Cannot make them readonly
As I have to change them for a certain amount of times
Kinda feels like you're trying to solve a problem backwards.
then go with one of the other mentioned approaches
or better yet - explain what you're actually trying to do so we can recommend a sensible solution
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
bool isLocked
struct thing {
int value;
bool isLocked;
}```
as mentioned before
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
?
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
ugui or ui toolkit?
i was using the textmeshprougui class for the text components, so whatever that is
does anyone know roughly what this error means?
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
help please?
It means you tried to change the parent of a Transform which exists in a prefab
you draw a graphic between the letters and blink it
anyone?
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?
if someone can help me why am I unable to transform that string into a date?
not without seeing the code
I just solved it by doing this ... writing the numbers in the shape of "yyyy-mm-dd" instead of "dd/mm/yyyy"
I thought try parse would parse the 2nd format
it will use whatever date format you provide, or the default if you don't provide one
I did provide one... it always parsed it as 1/1/0001
i can show you the debugs and code but it is not working
that''s your input string, not a date format
I dont know what you mean but my string was "27/3/2023" (without the "") as for the parsed value was "1/1/0001" as you can see in the picture above
That's what TryParse will output when it cannot parse the input
you need to make sure you are checking the return value of TryParse
ok but the thing is I thought it parses the format dd/mm/yyyy not just yyyy-mm-dd
if (DateTime.TryParse(...)) {
}
else {
Debug.Log("Could not parse input string");
}```
only if you provide such a format string
wdym
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).
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.
No problem, it's from my phone, so hopefully close enough to help
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?
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)
How will the serializefield help?
I have multiple gameobjects containing the script
You can drag the one object you want to call on it.
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
Can anyone help me, if I press enter on an empty input field it keeps giving an error
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.
Check if the input field isn't empty before attempting to parse the answer?
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
!collab
๐ข Collaborating and Job Posting
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
It works, doesn't show the error anymore tq!
I need to thank you again, it worked just how I wanted it to and I don't think I would've gotten it without your help so Thanks!
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?
Awesome!
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 ๐
Once you do this it doesn't matter what movement used to be:
movement = p_input.xAxis * transform.right + p_input.zAxis * transform.forward;
Well, first up, this doesnt show me when it is executed but the problem I'd assume is because you are setting rb.velocity = movement; but then changing it to 0 after, and next loop it replaces the 0 with the stuff above before assigning.
So my best guess is move the rb.velocity... line below the assignment.
Yeah
What they said ๐
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?
oh ok. thanks so much for the clue @leaden ice @west sparrow !!
transform.position - not relative to a parent, not relative to your anchoring settings.
I think you can do transform.SetParent(null, true) to keep the position after unparenting
Yea I must have something else going on bc that isn't working for me. Would the same be the case If I the set the parent to a different GO ? My first thought was anchoring but dunno how to mitigate that.
{
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
what's this about?
dropPosition.y -= dropSpeed * Time.deltaTime;
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
Also what's this for?
StopCoroutine(ShakeCoroutine(0)); < this almost certainly is not correct
it's supposed to move the spike downward.
but why would you do that here?
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
{
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();
}
}
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
does this belong in #archived-code-advanced ? I'm so confused
What could these be from?
They don't point to any specific script being the problem
just do a DFS to a depth of whatever your attack range is
it's true though that Unity's cell coordinates are weird
but it seems like your neighbors() function works
so you should be ok
could be almost anything that uses the job system
if you're not using the job system it's likely an internal unity thing
I am not doing anything with the job system so it must be unity being unity
thanks, just wanted to make sure it wasn't me
that's the strange part, it does work but once i start expanding it with other algorithms the shape become weird and wonky, for example it gives me weird ellipsoid shapes or squared. I can show you what other scripts I tried and the result
can you show the neighbors code
This might be helpful too:
https://docs.unity3d.com/Manual/Tilemap-Hexagonal.html
The coordinate diagram
trust me I read through it multiple times and also tried some conversion formulas from RedBlogGames but it goes beyond my tiny monkey brain
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
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
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?
basically this if you are able to see it here
https://www.redblobgames.com/grids/hexagons/#range
is Activity a custom class ? does it have System.Serializable
I'd just do a breadth first search or something
something like this:
https://hatebin.com/wjqkcypvno @rigid island
@rigid island Lots of learning material on hex maps here btw
https://catlikecoding.com/unity/tutorials/hex-map/
Not sure if there's anything pathfinding-related but thought you'd like it
NVM theres a pathfinding section too ๐
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
will check this out right now. thanks !
unfortunately pathing isn't an Issue since i got that already going with a*
I'm trying to do a range attack display per character
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
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?
Wow this works ! I can't believe the solution was this simple, no conversion or anything...omg
https://hatebin.com/speifugpjt @leaden ice
but I don't know why. All of my other events work fine
โค๏ธ much love @leaden ice You smart
just basic graph algorithms ๐ you can thank my Algorithms and Data Structures teacher in college from like 10+ years ago
how should i approach making an ai unit with custom movement jump on a navmesh? say jump is just adding some velocity to rigidbody
glad the knowledge was put to good use, haha dam I should've went to useful college ๐ฆ
Are you familiar with GOAP? Goal oriented action planning for AI
I'm making a prototype and was wondering what is the right pathfinding algorithm to look at. It currently uses a simple A* but I'm not sure if thats the right tool for this kinda job?
I've only heard the phrase, don't know much about it. Isn't NavMeshAgent an example of this?
It's not really spatial pathfinding like usual
But nodes that consist of actions and conditions
Isn't it more like how a mouse does pathfinding
without global knowledge of the space
Theres a world state that I feed parameters into and that is all the agent knows
So machine learning?
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
if I do rnd.Next(10)
will I get number 0,1,2,3....9,10?
or if one of those missing
No, I don't step into that realm yet ๐ GOAP has been used in video games (F.E.A.R. series, Halo, Half life I think)
Just for NPC behaviours
I'm still kind of wrapping my head around the whole idea
Not familiar with it
Alright, was worth a shot heh.
Damn I wish the AI channel was more active and not all the way down there
I feel it should be up here by coding lol
Yeah ๐ค Most questions seem to be about using the NavMesh but thats probably because its not in the code category
Do you mean System.Random.Next?
https://learn.microsoft.com/en-us/dotnet/api/system.random.next?view=net-8.0
yeah, I think it includes the min and not the max from what Im seeing
so Next(10) is 0-9
Yeah apparently the doc says it is exclusive upper bound
So 0-9
Just like unity's Random.Range int version
any reason to use one over the other?
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
gotcha...why would I use one over the other
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
gotcha thx
Is there a way I can stop object movement after lets say > 2 seconds ?
Hi, I'm doing a 2D platformer and was wondering if anyone knows the best way to do a corner correction like this https://twitter.com/i/status/1238338578310000642
4- Jump corner correction. If you bonk your head on a corner, the game tries to wiggle you to the side around it.
Likes
4220
Retweets
102
the best way...or a way?
first you have to say , how are you moving the object?
probably clever raycasting
I was gunna say collider checks, but Null is probably right
Ship.transform.position += transform.right * speed * Time.deltaTime;
simple ones
in update?
just make a bool
or set speed to 0
In 3D I would probably use this:
https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
But idk if theres a 2D equivalent ๐ค
Actually it could be this
https://docs.unity3d.com/ScriptReference/Physics2D.Distance.html
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?
yes, you can increment a value inside a coroutine each time an object is spawned, which in turn can determine the progress of a progress bar
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?
that could be one way to do so
This sounds like it could be it, I'll try it. Thanks!
depends on what kind of thing you want to do
is it something like, a structure being built in front of the player, and the progress bar is the amount of it built so far?
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
I havent used that 2D method, lemme know if it works for this
then ye, prob having some kind of empty parent prefab, and then spawn the sub-prefabs of it one-by-one via coroutine could be a fine solution
Alright, thank you a lot!
I'm using tilemap colliders btw, if that changes anything
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
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.
it sounds like you want a singleton. but it also sounds like you want that singleton to do too much
well i just want it to call functions on other objects when the properties it holds are changed
you should look into events and/or the observer pattern
alr i will
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?
another solution could maybe be to use a capsule collider?
trying to remember if unity 2d supports capsule colliders
it does
another question I have is if there's a way to stop unity from overwriting builds? if I want to make a second build so I can refer to the previous build later, is there a way to do that?
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
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);
}
}
I think you are setting the position directly rather than the speed.
so how would i set the speed?
should i set the y velocity of the controller?
The easiest way is to use a rigidbody, and changing the rigidbody's speed
but im using a CharacterController
I'm not used to using the character controller, so I'm not really sure. Sorry
OK, I think this might work but I don't really understand how to use that method, I only need to change the player's x position when hitting the ceiling corner. I can detect when the player should be moved, but not by how much it should be moved
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
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
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
anyone has a hack to open arbitrary cs file in IDE from editor?
nvm they are all MonoScript
when I do foreach for NativeHashMap / Dictionary, in which order does the loop go through? Is it defined even?
should be in sources
IEnumerator in the collection file
my guess its lower to higher
lower to higher what? key? what if key is int3/Vector3Int?
hash
hash is an int
Vector3 hashes to an int with spookyhash
youre doing spatial hashing?
nah, I'm just playing around with HashMap
all I needed to know is it's a defined consistent behaviour
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
then I need to store index in my value
im pretty sure that you should never rely on hash anything being consistent for iterations.
iirc java (or python) even has a built in randomizer to stop people from doing that, because it only works 99/100 times
haha
yeah, I will just store an index in struct that is value. this way I'll get consistent iterations
that means sorting every time you want to iterate?
or just having the position available
no, just looking up for correct index (writing and starting to realise it's just slow)
yeah this smells like xyproblem
just keep a separate array of the values for iteration
hashmaps are for lookup, not having an order ๐คทโโ๏ธ
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?
what do you mean by saying "if statement starts"
if (!someFlagThatWasNotSetYet)
return;
?
first condition not satisfied, it jumps to second, thats all that happens
when I put the answer, the if statement works fine but the else if statement just starts without even me putting in the answer.
second if() is not necessary, else is enough
yes because its in Update()
its called every frame
this means answer != GetCorrectAnswer() ๐คทโโ๏ธ
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
we don't know what GetCorrectAnswer() is, but presumably it returns a bool. And you call it every frame. I assume that when you haven't put in the answer (user input?), this method will return false, therefore your second condition is automatically met
yes it's just a simple math game, I put the correct answer Sprite moves forward. Wrong answer, sprite moves backward.
then have your logic wait until there is an answer
wrap all of the logic so that it only runs when answer isnโt "no answer" or whatever the default answer is
can also more conveniently define answer as nullable and check if answer != null
best to hook up a button to check
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
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);
}
}
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
enabling/disabling parent gameobject disables eveything inside it and its children (including attached scripts)
disabling components only disables that, allowing attached scripts to continue running
makes sense, thanks
i have this nre but it doesnt show anything when double clikcing it, can someone help
Is that the only error?
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?
it really depends on when you are calling CharacterController.Move since that is when the CC's isGrounded property is updated
oh really? So let's say I'm sitting on a block, and I call CharController.Move(). It will recongizes that I'm grounded. But then let's say the block disappears from me, so I start falling, but I don't call CharController.move(). Will it still think I"m grounded?
yes
hm
is it recommended to even use CharacterController?
why not just implement movement myself in my own script
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
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?
also you wouldn't start falling if the ground disappeared from below a charactercontroller because it doesn't have gravity automatically. you are very clearly applying the gravity yourself when you call Move ๐
right lol
Context.
source = GetComponent<Volume>();
source.sharedProfile.TryGet<Fog>(out var fog);
what kind of fog are you expecting this to be?
I am using URP with a global volume. I am trying to access the fog settings off of the Volume script.
Why does this guy make a Vector3 when the input is a vector2?
Does CharacterController.move() just require that?
this is my first attempt so not sure how to go about it.
I got the Volume assembly done and can grab the volume component, but just need this fog.
I don't know what this fog is? Does URP have a fog volume?
yes
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
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).
The input is a 2D vector, WS/AD or left/right, and the movement is in 3D space, XYZ
Which script, the fog script?
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.
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
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();
}
}```
If you're following a tutorial from Brackeys then that's your problem. Find something from someone else.
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...
it's this guy
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.
Do you know any resources where high code quality and professional software engineering standards are prioritized?
Yeah I gotta track down where I set it up and how one sec.
I know I did something through a tutorial for making it work with URP, but I am setting the fog through the Rendering/Lighting/Enviromental/Fog. Not gonna lie it might be powerful but the URP is super annoying to work with. Needed a few more rounds of UX design...
Yeah, it's a bit of a make work project.
I don't recommend using URP unless you have a usecase for it
I would study the .net side of things. Stuff like api/microsoft.core will be the best coding practices.
Unity can be a bubble of weird practices. And studying other C# industries will be the biggest eye opener.
Yeah well a bit late for that XD.
So are you trying to set the fog in the environment settings, or do you have a custom fog volume effect?
If it's just the environment settings, then I believe that's the same as the default pipeline, RenderSettings.fogColor
will test that
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
Well good news is that worked,,, bad news is that worked.
Is there an exception, and what's the contents of LoadMap?
There's no exceptions
https://hatebin.com/njulqhgcnw
I don't see why that would happen. Have you tried following it through with the debugger?
The scene is using URP as the renderer, my textures are URP textuers, but my fog is default render settings.
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
not a code question, but it looks like the rect is reversed
why not?
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).
The context is simply it's UX is very bad.
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.
So invoking the method 2 seconds later fixed the issue
I guess the scene loading caused it
Nevermind, it broke again
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 ๐
Easily share your source code with other developers.
(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.)
There are many ways to see the logs from the build running on your phone.
Not just logs, you could even connect a debugger and step through the code with breakpoints.
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.
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.
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?
the lines before it could be throwing
put in a try catch if you want to double check, can then log the exception to the touchDebug.text
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.
Okay, not used trycatch in a while, this'll be fun.
Connect the console or see the logcat for wether there are errors thrown.
You're debugging backwards.
Don't do that.
Man, really wish I didn't have to set up more apps for a small assignment, but okay.
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.
When I do build and run, I need to use the development option then? I'll try logcat first.
Yes. But logcat is a better option.๐
Ok, lets see if this reveals anything, probably not though, GetComponent really annoys me at times.
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
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
look at line 26
Steamworks.SteamUserStats
line 27 and 28 are just SteamUserStats
so try Steamworks.SteamUserStats there instead
uh, actually you have the using statement
humm, strange
yeah, I tried that now, but I get the same errors ๐ค
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?
with .Add()
lmao I was trying to use Insert. I assume that if something errors the proceeding lines of code wont work either?
That would explain a lot.
yup
If this works I will be happy and also kinda seething.
my fking god. Thank you @lucid valley
how do i get the time elapsed since the previous while loop iteration in a coroutine
if you're just yielding null then that's the difference between frames, Time.deltaTime
ohhh
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?
yes
i see
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);
}
}
Hello, how should i handle i/o threads in unity? Create .NET thread or event native thread from winapi?
bois
ladies and gentlemen
how do I compress images permanently
not just like a build thing
Use rigidbody velocity, dont calculate it yourself
Subtract ship velocity from planet velocity => get relativevelocity. Then use dot product to cast it onto axis of choice
hey everyone, does anybody know why I keep getting this error or how to get rid of it?
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);
}
}
your player doesn't happen to have a slightly weird rotation does it?
"rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.y);" you are setting your player's rb.velocity.z to their y velocity
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...
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.
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
i've never worked with something like that. could you please share the syntax on how I'd use Path.Combine?
string good = Path.Combine(path1, path2)
thanks
(you can pass more than two arguments if needed)
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
Thanks, Ill try doing that with my caulculated velocities, I would do it with rigidbodys but the planet needs a non convex mesh collider which doesent work with rigidbodies
I have this code (the sample code for FPController), and everything works fine in the Editor, but when I export the project, I can't look up and down. Does anyone know why?
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
im proud of you shrek
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 ?
Why not just use one of the many existing serializable dictionary solutions out there
Or just make a list of key value structs
I would just be googling it and taking the first result
oh wait im dumb i didnt import the ditor at the time because i didnt know what it was
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?
What did you use to make the requests? Unitys WebGL can't use some network functions, so you usually end up using BestHTTP. I believe normal C# web requests don't work? Sockets don't. But you can use Unity Web Requests.
I'd also give this a read, because cors, and http vs https
https://answers.unity.com/questions/1598212/unitywebrequest-not-working-in-webgl-build.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I tryed with Coroutines than tryed with async functions nothing work on build but in editor works fine
Yup, read the above
hmm...on forum its saying like my url trying to access http but i defined url that starts with https
your planet is not convex? :S isnt it a sphere?
It has terrain so its sadly concave
but why would that stop you from using rigidbody phyisc?
cant you just attach the terrain to a child object?
Does that work
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 ๐
Well sadly that is sometimes jow unity is
One limitation so you have to do ever,thing from scratch
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!
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);
not entirely sure but that code seems like a race condition since you're incrementing y in a different thread than you're consuming it
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
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
i cant tell where your error comes from, but this whole code looks like it wants to be a shader.
ohh yeah thank you. Works fine when using a seperate variable
you can sample the area of the player.
just from the top of my head i would sample random points inside the players boundingbox and cast maybe 5 rays towards the enemies eyes.
if any of them hit, enemy has detected the player
if your player has a simple geometry, sampling points inside it is even easier.
Just to see if I'm understanding correctly, you would cast the rays from the players bouding box? Or could it be done from the enemies eyes to the players bouding box?
doesnt matter i guess, if it intersects, it intersects
I've got another question. Why is the syncronous code running more than 170 times faster than running the multithreated code?
Sometimes the overhead of starting threads and coordinating them outweighs the gains you get from paralellization
although it's also possible your code is flawed in some way
I didn't read it too closely
Gotcha. How would you personally determine which random points to cast towards? Do I just use the size of the bounding box (in this case a capsule collider) and divide accordingly, or is there some other way?
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
Yeah, I guess this is similar to how I used the circle collider at the top of the head as a workaround. I'll see if this could work.
And I'll read up on the sampleUnitSphere since I hadn't heard of it before
Thanks for the suggestions and the clarifying drawing, I'll see if these methods solve my problem :)
its a common problem. in early Arma 3, you could hide behind street signs, bc it would hide your face from the enemy
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
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
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.
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
Yeah, thats true. Then I'll probably try what you mentioned earlier of casting to points of the bounding box.
if your game has few enemies/players, you can probably go a bit crazy on detection performance.
Only the one player, and a couple of enemies scattered around different levels, since it's also supposed to be a platformer
how would I store unique data on each tile using tilemaps?
I believe you would have each tile represented with a scriptable object
could be wrong though
GameObject?
alright
But how would that work Tilemaps?
I assign that object to
each tilebase?
ah np
I think codemonkey has a heatmap video that might be of some use
how do i calcualte the angle a 2D gameObject is moving in? ive been searching the internet for about an hour with no avail
wdym calculate the angle
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
wasd?
Vector2 input = new Vector2(horizontalInput, verticalInput);
float angle = Mathf.Atan2(input.y, input.x)
i think
angle on the transform is a local space angle, but thereโs a readonly worldspace angle on the transform called transform.lossyScale
other way
take your time
thereโs also Vector3.Angle for between two objects
try this
could i make an empty follow the target object with an offset and use vector3.angle?
atan2 should work
whatโs wrong with MoveToward()?
Then thereโs Vector3.Lookat or something like that to line up normals
@upper pond did u try it?
im editing the variables rn
when i turn it into a public float the angle is just saying 0
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector2 input = new Vector2(horizontalInput, verticalInput);
float angle = Mathf.Atan2(input.y, input.x);
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?
there is extenject and other maintained libraries
the angle is just displaying 0
{
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
dont understand what youre asking, the code is valid
I'd like to compare two Quaternions after using Slerp to dermine if the rotation is finished, with a margin of error, how? RESOLVED
Is there a way to manually iterate over a shader variants collection?
I wonder - has anyone managed to invoke Rustc lib inside Unity, and any pro/con doing this other than malloc for CAPI calls?
any idea why a quintuple nested loop would cause 170ms garbage collector frame spikes?
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
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;
}
}
}
}
}```
foreach is probably what's generating garbage collection...
yeah probably
and good god man.. Why so many loops?
I'll swap it out, 1 sec
I'm making a battle simulator, so I sort all soldiers into a grid in order to do checks between them
Possibly that Linq line
hmm I was suspicious of it too but I couldn't be bothered to find a better alternative
Yup, Linq will most definitely allocate garbage!
Now you can be bothered to!
Why do you need them in order? I don't see a reason why?
to find the closest
Why?
Picking targets likely
Would consider relying on physics cast instead of checking distance?
oof no
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
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
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.
....which is what I'm doing
There must be something like GDC talks on the subject
In fact, all of this is on main thread, talk about halting your program for a sec here.
Dots would be a good usecase here yes
you just said "oof no" to a suggestion of using some cast/query though
I said oof to using unity physics for it
it shouldnt be
"physics cast" referring to the same thing i was referring to
alright, I misunderstood then
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
Is there a command like this but will not work when it is held
GetKeyDown
yep that one, thanks
when displayed as a float it says 0. is there any variables i needed to make?
im a dubass. I put all the code into a void but didnt call it anywhere
happens to me about 7 times a day
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 ๐
anyone know what this means
you have code that isn't inside of a class
yeah thats what i thought
nothing is outside tho
nvm
sorry
i had brackets outside
thanks
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
Who are you sending it to
literally anywhere, even in my own servers
oh
Your application might not have permissions
Check the Discord Application
In Developer portal
In general information I think let me see real quick
i dont see anything
uh... now im confused what to do because i need a redirect url
Ah can I see your invite code?
nvm hang on
You will need a redirect url
I think I used my IP
before I forgot honestly
@crystal creek Use this
http://127.0.0.1
what scopes do i need
rpc
This should allow your application to access your discord client if I'm correct
hm
Also In OAuth2 add in redirects the same link
Show me your invite code
as I said before
it must be a problem from your code itself
u mean the generated URL?
also prob better to move this to dms
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?
how can i play a sound for each particle's birth in my particle system?
using static will preserve your result at editor-time. However beware about unity's domain refresh option!
I need the cached field info to be non-static, and it appears the domain refresh applies for all scripts, when I only want to do this for a select few.
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
whats the context?
I want to take how long you pressed and after that time passed stop jumping
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?
for the one line if statements, you can remove the braces
I know
public static void Main()
{
public void Start()
{
HouseKey = GameObject.Find("HouseKey");
}
public void Update()
{
Debug.Log(HouseKey);
}
}
But somehow for me it maintains my code cleaner
i cant find that specific object because i switch between scenes and come later to that old one
the object is deactivated
this is why i cant do public and assign it
its like impossible
i don't understand your question or your purpose but, that's StartMethod by the time you click Play Button on unity, it will start search the HouseKey, Run only Once.
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
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)
Did you place logs before and after the yield for 1 second?
No
what is that supposed to be?
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
Where are crash logs for a build? Not the editor
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?
Okay, I got the camera thing working, how would I go about making the main camera use the skybox camera as a background?
#854851968446365696 on how to ask a proper question
solved the problem :)
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
Raycasts have a length option