#archived-code-general
1 messages ยท Page 47 of 1
make a method without a return type
I kind of need the return
The button cannot use it, so no
Make another method that calls the one that has the return, and doesn't return it
Ah that worked thx
How can I use something in a Unity scene as a reference for a prefab? So like, I need to reference my script where the int points is, but I need to set it to an instance of an object, but the editor won't let me.
Pass it to the prefab when it is instantiated into the scene
hi all
Flash question, Just updated my Visual Studio 2022 then this happen. The simpleJSON shown a error and all related to JSON. Plse help me
Make it a static variable
try going to Edit > Preferences > External Tools, then Regenerate project files
Thanks, I already got it. Used FindWithTag("Text") to find the object the text was attached to.
Thx man, save my day. Thx for the knowledge
does &= exit early if the left-hand side is already false?
because it is x = x && y, presumably yes
& doesn't short circuit though, it evaluates both sides every time. it's && that short circuits
so &&=?
"Did you mean &&="
if I want to avoid the RHS evaluation
cool
i meant x && y i am tired ๐ฆ
I am unsure if it will always compile that way and bypass the check; you would have to check the decompiled results of what you've written.
For example changing the code I used to:
bool a = new Random().Next() == 0;
a &= new Random().Next() == 0;
results in &=, which is unclear to me, and I can't read IL reasonably
fun fact about sharplab if you didn't know, you can hover over the IL and it tells you what it is doing. from what i can tell it's doing basically the same thing for each. the only difference seems to be when it is loading the variables on the stack
I know I can hover, I still can't read it well enough to be able to compare
Ah, here we go, you can see it doesn't skip evaluating the second argument when it's actually something that can be evaluated
https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQyDMABGgQMICGBA3jgbUYcgCwECCAFAJRU128BGAewEQCFALwEA4gFNg7DgG4evWhQBkEmcABCnJdl4BfZQRP4izXV2oGVtQcNEFNs+frurnTtVNlX3dMa2tGYMzCSc3MEqDiLivnJ6Jrzx6j5a/iZBvKEEsQnyzgB8BAB20gDuBABKZKUwAgC2nAB0AHLSAB7AkWISAAwBtOb5Gb0l5VW19U2tHd29A/qGQA=
The previous example was just an interesting note that it all compiles to the same thing if the arguments have previously been evaluated (which may or may not change if it wasn't compiled in Debug mode)
Hey does anyone know if theres a way to Have 1 state in an animator layer that doesnt inherit the avatar mask of the layer?
Would make more sense to ask in #๐โanimation
ah sorry i just thought it would only be possible in script
Pretty sure that if it's possible, its done in the animator window. But I suspect it's not possible
In any case, even if it ends up being code related, people in the anim channel would know better
i have navmeshsurfaces in a level and i buildnavmesh at awake. when i see it in navigation tab navmesh seems fine but agent cant calculate path?
any ideas why its not working
it worked when i change collected object to all in navmeshsurface component
Is your level generated at the start or why do you build the navmesh at runtime?
yes my level generated at start
i have different levels thats why i instantiate them
What language is this?
I got the wrong discord, it's lua ๐
Looks like Roblox. This is a Unity server, you're in the wrong place
sorry
Hi! What's something you could use as an alternative to OnTriggerEnter2D? It doesn't work with 0 timescale and I've tried Physics.OverlapBox but that doesn't seem to work either for some reason.
You'd have to use Physics.SyncTransforms after moving objects if you want queries to see updated positions
Okay thanks.
I think it's not really coding related but any ideas what's causing this? When moving the player it randomly skips frames(?) and player is somewhere else
Another example
Most likely culprit is your code
looks like it's position is getting reset
Hello, this is driving me crazy as I've done this many times before.
I have an object, when I drop it anywhere on the screen I want it to tween to a position (using DoTween). I was using startpos from another class to do this but noticed an issue where it would snap back to where my mouse was last positioned.
To try and simply this, I hard coded a value in but still get this weird issue where it moves back to my mouse position despite the hard coded value.
I then tried to use a simple transform.position which worked without issue - my object always moves to that position.
Any idea why DoJump moves to the correct position but then seems to move again afterwards?
var startpos = new Vector3(23f, -0.26f, -107f);
transform.DOJump(startpos,5f, 1, 1f).SetEase(Ease.OutQuad);
//transform.position = startpos;
Do you have a Rigidbody
Or CharacterController?
@leaden ice I actually didn't use either but even after adding a rigidbody the issue is still there.
Also worth noting I just tested again and it worked 9/10 times before failing to stay at that hard coded position so its pretty inconsistent at the moment
I never said to add a Rigidbody
Anyway you'd have to show more code then
Presumably you have other code changing the position
(or some other component like mentioned)
How did my game go from this in the editor to this in game
this is a code channel. perhaps you want #archived-lighting
ok
@leaden ice Got it, I was putting together some sample code to share and found the issue. I was setting the drop state twice so it was causing the code to re-trigger
I forgot that code was related when I was doing my debugging
by the way, what is the best way to register an account on the unity, I just chose a google account
Not a coding question. The best way is one you'll remember.
It's clear
Can someone give me a pointer on how to get the health bars (slider bars in world canvases, children of each unit) to sit in front of the current unit but not overlap units in front? Tried messing with render queue in shader but seems to not do anything
Hey, noticed this problem does not occur in build, only in unity editor. Not sure why though
it doesn't look like a normal or common issue - it's likely up to you to review your code and troubleshoot exactly what's happening
does anyone know how to change properties of an object that has been picked up by ontriggerenter
I'll do that yeah but it's interesting that it only happens in editor
it's an interesting observation but I'd probably not assume that's the case until you're able to narrow it down further
What sort of properties do you want to change? col is the incoming collider so you can get components from that
well i would just like to turn on and off the mesh collider, could I just reference it as col.MeshRenderer?
The mesh collider of the other object?
oh wait im pretty sure I have to use get component
yes of the object that was collided into with the tag "Ball"
Mesh collider or mesh renderer? (you said both)
oh sorry i meant mesh renderer
Yep then use col.GetComponent<MeshRenderer>()
Or TryGetComponent so it does a null check basically
oh okay yeah i thought it would be something like this thank you
so if i were to turn it on or off i can just put that in the brackets?
nope thats not it
oh no I do GetComponent<MeshRenderer>().enabled = false;
okay that seems to work thank you for the help @hexed pecan
Simple question, what's a variable type that doesn't show in the inspector but can be accessed from all scripts?
Do you need every instance of that class to have its own value? Or one global value?
One global value
With public private and whatnot basically
Those are called "access modifiers"
Ohhh
Sounds like you want static
Okay thanks
Hi guys does anyone know by any chance where can I look into how-to cache images from unitywebrequest?
Is it possible to add a function to an enum, or conversion rule? What I want:
public enum EFoe {Friend,Foe}
class Something
{
private EFoe state = EFoe.Friend
void DoSomething()
{
if(state.IsFriend)
{
//DoStuff
}
}
}
RN the best I could come up with is creating a wrapper, it works I guess but it is relatively bulky (more stuff to type out):
public enum EFoe {Friend,Foe}
public static class IsFoe { [MethodImpl(CMath.INLINE)] public static bool Bool(EFoe p) => p == EFoe.Foe; }
class Something
{
private EFoe state = EFoe.Friend
void DoSomething()
{
if(!IsFoe.Bool(state))
{
//DoStuff
}
}
}
Is there a better way?
Is there a way to debug the raycasthitpoint visually? Like debug.drawRay but instead of a line just a big ball for the hitpoint?
I've written myself a function for something similar:
/// <summary>
/// Trace line as bool
/// </summary>
public static bool TraceLine(Ray ray, float distance, int layerMask, QueryTriggerInteraction ignore=QueryTriggerInteraction.Ignore,bool debugDraw = false, Color? clr = null, float drawtime=0)
{
RaycastHit hit = TraceLineRC(ray, distance, layerMask, ignore, debugDraw,clr,drawtime);
return hit.transform != null;
}
/// <summary>
/// Trace line and return hit
/// </summary>
public static RaycastHit TraceLineRC(Ray ray, float distance, int layerMask, QueryTriggerInteraction ignore=QueryTriggerInteraction.Ignore,bool debugDraw = false, Color? clr = null, float drawtime=0)
{
RaycastHit hit = default;
bool result = Physics.Linecast(ray.origin,ray.origin+ (ray.direction * distance), out hit, layerMask, ignore);
#if UNITY_EDITOR
if(debugDraw)
{
float time = drawtime;
if(time <Time.deltaTime)
time = Time.fixedTime / 600;
Color devColor = Color.green;
if (clr != null)
devColor = (Color) clr;
DebugWireSphere(ray.origin, devColor, 0.01f, time);
if (result)
{
Debug.DrawLine(ray.origin, hit.point, devColor, time);
Debug.DrawLine(hit.point, ray.origin + (ray.direction * distance), Color.red, time);
}
else
{
Debug.DrawLine(ray.origin, ray.origin + ray.direction * distance, devColor, time);
}
}
#endif
if (!result)
hit = default;
return hit;
}
that looks promising, i will look into that. Ty
thats a bit over the top for me ๐ . But thanks anyway
does Physics2D.Linecast Automatically hit triggers or do I have to turn that on
depends on the queries hit trigger setting in the Physics2D settings
UnityEngine.Mesh.CombineMeshes (UnityEngine.CombineInstance[] combine) (at <7b2a272e51214e2f91bbc4fb4f28eff8>:0)``` is there any way around this? The `CombineMeshes` function is quite useful for what I'm doing, but I don't see any way of specifying the integer format of the index buffers
By the way, I also wanted to ask I didnโt notice in my personal data
I'm about Timezone
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
yep, figured it out in the link after my post
When should I use jobs?
I want to use it, but I feel like it's a lot of boilerplate code
If you have processing to do which benefits from threading.
IE can run for a while without holding up everything, can't be completed in a frame, and can't meaningfully be sliced.
Does anyone know of a good method/design pattern for creating a singular UnitAnimator script that can trigger different animations based off a wide list of ability's that different units could have. I dont want to have to go in and hardcode the strings for each ability. Is there a way to store the animation in the ability data and trigger it through code?
how i can change this code to a code with overlap sphere that sets ui position to the object that have a "interactable" script that is the nearest to the ray point???
RaycastHit hit = RaycastPlayer();
if (hit.transform != null)
{
//Hit something
GameObject hitObject = hit.transform.gameObject;
Interactable interactable;
if (hitObject.TryGetComponent<Interactable>(out interactable))
{
Vector3 UIPos = playerCameraInstance.WorldToScreenPoint(hitObject.transform.position + Vector3.up * yOffsetInteraction);
interactionUI.position = UIPos;
}
}
you could use AnimatorOverrideController... but i never done to code animator if you just want to play ddifferent ainmation with different units.
i don't knonw but, i was thinking you can store each hit point that have interacble and then search with sqrMagintude or Vector3.Distance.
so every object that overlap with sphere, add to a list/array/anything and then loop them
foreach(GameObject myinteractable in intracbles)
{
var testing = myinteractable.GetComponent<intracbles>();
// check nearest
// do something.
}
i don't know if this will help...
id guess some amount of sphere casts at different distances may be the answer. Or potentially shooting out a range of raycasts, kind of like a shotgun blast, instead of just one
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
Good morning community. I'm struggling with an issue regarding scaling a prefab instance during runtime. The code works, but the instance does nothing in the game scene. Local scale shows as updating but I believe it still holds the overriding local scale of the prefab. Any advice?
That was it. Thanks
Does anyone know why i cant set animation curves in bulk inside UnityEngine, But the UnityEditor.AnimationUtility has a bulk method called AnimationUtility.SetAnimationCurves
:\
cant use it on runtime, my animations are all generated on runtime
is there any way i can pull in unityeditor ref on my build?
the Animation itself has animation.SetCurve but this isn't a bulk
nor can you get animation curves on runtime without accessing unityeditor
I cant serialize animations then load them cus theres too many combinations...
๐คฏ
float horizontal;
float vertical;
public float speed = 10;
void Start()
{
GameObject.GetComponent<Rigidbody2D>();
GameObject.transform.position = Vector3.zero;
}
void Update()
{
horizontal = Input.GetAxis("horizontal");
vertical = Input.GetAxis("Vertical");
gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
}
Hi I'am trig to make an object move constantly to the right, but for some reason it doesn't work, can someone help me?
what is this code supposed to be doing
void Start()
{
GameObject.GetComponent<Rigidbody2D>();
GameObject.transform.position = Vector3.zero;
}
For some reason ur getting the RigidBody2d reference and not assigning it to anything. Then your somehow calling GameObject.transform statically ?
Then when you use Update() you use gameObject with lowercase
it suppose to set the ship to the 0,0,0 position
No that code wont even compile
Not too sure maybe you left code out?
the rigidbody it's for something else, doesn't matter
so what should I do?
public class PlaneMovement : MonoBehaviour
{
Rigidbody2D rb;
GameObject GameObject;
float horizontal;
float vertical;
public float speed = 10;
// Start is called before the first frame update
void Start()
{
GameObject.GetComponent<Rigidbody2D>();
GameObject.transform.position = Vector3.zero;
}
// Update is called once per frame
void Update()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
PMove();
}
void PMove()
{
transform.rotation = Quaternion.Euler(0, 0, rb.velocity.y * 2);
if (vertical > 0 || Input.GetMouseButtonDown(0))
{
rb.gravityScale = -4.314969f;
}
else rb.gravityScale = 4.314969f;
}
}
Nvm
use
GameObject.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
A variable named GameObject...
Subzero its not too clear what object your trying to move lol
@swift falcon Check this
You have a GameObject ref inside ur code, you are moving the gameObject of the script
would you like to move the rigidbody?
I want to move the object associated to the script
can you take a picture of your script attached to the object
e.g. mine
hmm seems speed is fine
no clue it should work lol
thanks I solve it, it was the blue GameObject variable
You might want to remove this dead code
GameObject.GetComponent<Rigidbody2D>();
GameObject.transform.position = Vector3.zero;
It does nothing
Your GameObject variable is never set, im suprised you dont end up with a null pointer exception
I don't know why I put it in there
jajajaja
thank you so much
np ๐
i have a door script that can open and close my doors pretty nicely but the issue is if you spam the door open button the door starts bugging out and throwing 360s on me so i was wondering if there is a way to check what the animator is currently playing so i can make so if the door is in the middle of opening or closing you cant use it. here is my code i dont think it matters but i put it here anyway just in case
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour
{
public bool DoorUsed = false;
public bool DoorOpen = false;
public Animator OpenClose;
// Start is called before the first frame update
public void Start()
{
OpenClose.Play("Closed");
}
// Update is called once per frame
void Update()
{
if(!DoorOpen && DoorUsed)
{
OpenClose.Play("Close");
DoorUsed = false;
}
if(DoorOpen && DoorUsed)
{
OpenClose.Play("Open");
DoorUsed = false;
}
}
}
Do it in the animator state machine
Nvm I misunderstood I think
Transitions with has exit time enabled
yeah you can use clip.AddEvent(animationEvent)
if you want it on a specific frame, i think theres a few events onAnimationstart
and end
Although not sure why you'd handle door animations using the update function and a boolean
how else could i do it?
What you can do is have a method to Open and Close the door.
private boolean _opened;
public void ToggleDoorState(bool open) {
_opened = open;
OpenClose.Play(_opened ? "Open" : "Close");
}
No update method and boolean check required every tick
to Open the door you'd do:
door.ToggleDoorState(true); to close it you'd do door.ToggleDoorState(false);
what does _opened mean
if the door is opened already (default false)
its a boolean
You use "doorUsed" and "doorOpen"
When you only require a single boolean to denote a doors state
you can even get more smart with it and use doors.Toggle();
which would do:
public void Toggle() {
ToggleDoorState(!opened);
}
If the door is open it will close it
If the door is closed it will open it
okay so like
i'm using a very ancient version of unity
and i can't seem to access "unityscript.lang"
Anyone help with this ๐ญ #archived-code-general message
Sad i cant use unityeditor lib inside build
blocker
:[ inb4 i have to use the cloud to make the animation with unityeditor lib
and ondemand feed it into the game client
Why? Not many people will know how to help with old unity versions
i honestly couldn't find anywhere else to find help
i asked here just in case
Thats true you cant
Dont get me wrong this is the right place to ask, or the forums
is there anyway to swap it like you know how you can do bool = !bool to make it opposite so how would i do that with this?
if it is even possible
@crude marten
oh i forgot about that sorry. thank u
Is there a way to count how many a character appears in a json text file? I'm looking online and there's similar questions with answers in the form of code , I was maybe looking for a text editor that could do it
example
if I wanted to count a remove all but 1 "a" in the following json imgae
what is the unity idea here
Question about using interfaces - imagine an old school JRPG like FF2 or Dragon Quest. The player has spells, some which can be used in combat (say, Fire) and others than can be used on the Overland Map (Teleport), and some that can be used in both, for eg Heal. Using interfaces, like ICombatSpell, IMapSpell seems like it'd be appropriate because spells in each context would require distinct data (ie, combat spells have a target), but that leads to having to make a concrete class for each combination of interfaces you want, whereas most of us would conceptualize when you can cast a spell as a property of a spell - you'd check a boolean for "isCombatSpell" or "isMapSpell" or maybe something more in depth.
What is the traditional approach to this issue?
gizmo is drawing agent.path. Any idea what could be causing this?
the traditional (stupid) approach is to use the full force of OOP, multi inheritance and a godly master baseclass. luckily in unity you don't have to do that, and its also not the 90s anymore so you use components and forget about interfaces... if you plan on using a dependency injection container or some other sort of system that you build outside monobehaviours go for interfaces and IoC. Generally you'd make small interfaces that express and Aspect/Capability of something, e.g. ICastable, ICollectable, IDamageable, and compose these in whatever way you like on the implementation side.
so basically just roll with making a concrete class for each combination of interfaces?
the path is updating correctly, it draws the path from the zombie to the car and draws the gizmo directly from the path variable of the agent
but the zombie just isn't walking that path
lemme grab the code
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.
as i said, you can compose that on the implementation side whichever way you like (thats the whole point of interfaces, they do not imply any specifics on the impl side, unless you make leaky abstractions), classes implementing multiple interfaces or just a GameObject with a bunch of components implementing each one separately and all called from some sort of "engine" that ties the whole thing together
"leaky abstractions"? I'm not sure what that means so I now I'm worried I'm doing it ๐
now that i've learned about the word for this you should briefly check out unreal's "gameplay attribute system" which is a unified approach for this sort of stuff
a leaky abstraction is when your interface makes assumption about how the outside world is constructed/behaving
since you have a limited number of spells keep it constrained
when you know exactly what spells you want to implement, it makes more sense to write it in a strongly coupled way
that means you would have your GameSpells class, and allow it to grow organically
Random question about scripting.
I have to explain a script within a word document.
Would the best approach be to do this:
Paste the script
Explain it fully in Psuedocode
Then explain more precise details after
yeah, alas, I used the spells as a simplified version for the discussion, i'm actually doing this for action types. I'm kind of imagining a functionally unlimited of combinations, block action, attack action, melee action, etc.
and add the bits and pieces you need to implement the spell in the right places. instead of interfaces, think about how repeating behavior can be a function you call in multiple places, rather than an interface you expect on a component
i see what you mean. the general problem of "how do i do LISPs in unity" is tough. it's really important to not metaprogram inside of unity
LISPs?
so to express a combat behavior as a sequence of these actions... write a method that does the actions.
don't try to program inside the inspector
oh yeah this is very much not inspector or game-object driven. but I want to like, check if the incoming damage implements ILightningDamage if the player is standing in water or whatever, but I don't want to create a damagetype class for my omega weapon that implements ILightningDamage and IFireDamage and IEarthDamage etc etc. I would do more of a "tag" system but I do want to enforce some contracts on these types, like if it's IMultiTarget, I should be able to access IEnumerable<enemies> Targets or whatever.
for example.
public class Actions {
// returns the actual amount of damage dealt
protected int DealDamage(int damage, Character target) {
...
}
// returns summoned character or null
protected Character Summon(BaseCharacter baseCharacter, int position) {
...
}
...
// used by: Necromancer, Lich King enemies
// Deal {damage} damage. For each target that dies, summon a {character}.
async UniTask Fireball(int damage, BaseCharacter baseCharacter, List<Character> targets) {
foreach (var target in targets) {
DealDamage(damage, target);
}
var died = await GameManager.instance.currentGame.EndOfSequence();
foreach (var didDie in died) {
var position = didDid.position;
Summon(baseCharacter, position);
}
}
...
}
dont make an interface where an Enum is sufficient
Hello guys, I'm currently working on a parkour system, I'm currently working on walking on railing feature but I'm having trouble figuring out how to do it. Can someone give me a solution? Thanks
okay you're way past my example, give me a sec
I would probably just do an array of damage types in case like this
public class Actions {
// returns the actual amount of damage dealt
protected static int DealDamage(int damage, Character target, DamageType damageType=DamageType.Physical) {
...
// check for immunity
if (target.attributes.immunity.Contains(damageType)) {
damage = 0;
}
...
}
...
...
protected static void GrantImmunityTo(DamageType damage, Character target)
{
...
}
}
@ionic socket
also, observe that with this approach, you can progressively add functionality
this is what i mean by strongly coupled
you do not need to add a trait to the fireball and water canon spells
via an interface
in their specific function implementation,s they will just call DealDamage with damageType set to whatever
you don't want DealDamage to inspect the class of its caller
it should basically be stateless
hmm OK I see what you mean
i modified the methods to be static to emphasize the point
it's called "gameplay attribute system" because you wind up writing a ton of these
and they don't really exist on classes
they are just a dump of data inside a dictionary (i.e. attributes)
in this particular case attributes can be something like
I think this is similar to what I meant by a Tag system. and I suppose the tags themselves can be arbitrary data containers and will emulate (for my purposes) the utility of Interfaces. Like a single vs multi target attack could have a SingleTarget "tag" which itself is a class that just stores a target; whereas MultiTarget stores an enumerable.
class Attributes {
DamageType[] immunity;
// get by name
object this[string name] {
switch (name) {
case nameof(immunity):
return immunity;
...
}
}
}
or
class Attributes : IDictionary<Attribute, object> {
DamageType[] immunity;
override object this[Attribute attribute] {
switch (attribute) {
case Attribute.Immunity:
return immunity;
}
}
...
}
yes, just keep it super simple
the "attributes" container of this system should hold immutable primitives and be easy to copy, since you will be copying it a bajillion times
you don't want to store weird shit like polymorphic classes inside of it
haha yeah. I can sometimes get caught in the abstraction k-hole.
you will want int GetValue(Attribute attribute), assuming the caller knows it will be an int. store everything inside a property OR a dictoinary. you can also access the properties semantically, like i whosed in my example
for the sake of readability
you can also mark these properties as virtual and do not declare IDictionary
if you want to be safer
is there a good way of going about customizable keybinds? From what I can gather the easiest way is getting a KeyCode from string, but that seems rather janky to me
?
interface IReadOnlyAttributes {
IReadOnlyList<DamageType> immunity { get; }
}
class Attributes : IReadOnlyAttributes {
public override IList<DamageType> immunity { get; set; }
= new List<DamageType>();
}
@ionic socket in my experience, decisions like these are much more impactful for correctness
that's really vague, we are gonna need more information to work with
What's a good approach using interfaces on components? Considering that you may want to create dependencies in inspector and so on?
https://pastebin.com/p29ts8Bf Is there some better way than doing something like this?
class Character {
Attributes m_Attributes = new();
public IReadOnlyAttributes attributes => m_Attributes;
public Attributes mutableAttributes => m_Attributes;
public Attributes GetAttributes() => m_Attributes.Copy();
}
Iโd really appreciate some help here
I'm aiming for something like this https://www.youtube.com/watch?v=hbAcF036mLk
it looks like there's an issue with the turning speed of the zombie or some lag time in how quickly it updates it's path.
That makes sense. How would you recommend I fix it?
nice plagiarism xD
Sorry I donโt know a whole lot about navmeshes
A hacky way would be to swap your movement over to a navmesh whenever you're on a railing
that should allow to only be able to walk on a certain layer
I'm sure there are better solutions, but that's what I can come up with on the spot
boxcasting probably
never thought of that honestly
check each side of the character
angular speed does not have that large of an effect it seems
can you post the link to your code again?
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.
Any ideas? running on mobile web browser
the intended behavior is that the zombie should turn and move towards their target just like the gizmo does?
yes the zombie should target the car more accurately than it does now
_contactTimer might be too high, it looks like that prevents the zombie from choosing a new target?
i think contact timer is for attacking the player. let me double check for you though.
oh actually
you know that may be a good point
Anyone have any input on this?^^
so contacttimer is just a cooldown for how long the zombie has to wait before they can hit the car again
it's not explicitly tied to pathfinding, but the pathfinding function will call cancelmove if they have to wait before they can hit the car again, which doesn't affect turning or the ability to accurately track the player from what i can tell
public void Open(int index, string menuName)
{
var menu = Instantiate(interactionMenuTemplate);
menu.transform.GetComponent<Canvas>().enabled = true;
menu.SetMenuTitle(menuName);
menu.SetOnCloseAction(() =>
{
Destroy(menu);
_menus.Remove(menu);
});
_menus.Insert(index, menu);
}
For some reason I can not Destroy those prefab instances I created within an event callback.
As you can see in the screenshot the InteractionMenu(Clone) keeps stacking up.
I also tried DestroyImmediate just to be sure destroying does work at all
how could you go about rotating a transform over time?
I have this line player.rotation = Quaternion.Slerp(currentRotation, targetRotation, Time.deltaTime * rotationSpeed); but its super clunky
Hey guys i have this problem for a while now, basically i have this model that i want to make it follow me, the animations plays all good, perfect, but it doesnt move, i was suspecting it is the code, i want to make sure it is correct.
The script: https://hatebin.com/paywqfmwyo
start() -> Start()
Are you setting followingPlayer to true anywhere?
Are there any errors in the console?
nothing
i had this problem before, but i dont know how i fixed it
Your animator is constantly overwriting the transform.position
then how do i fix that
Make the nav mesh agent a parent of the animated object
Animator shouldn't move the root of the character. It should only animate bones.
k
ohh
i get it now, The object that contains the NavMeshAgent is trying to move, but the FollowingPlayer animation is on a specific position and it cant move because it is on that position still, because that is where i animated it, right?
Correct
so i have to create a gameobject with the navmeshagent that will be the parent of the old navmeshagent?
Either that or the very complicated task of not using animations that conflict with transforms
that includes rotations
The former is a lot easier to work with
The "former"?
The first option suggested
bruh now he plays the animation on the corner of the map
i tried reseting the pos
the hieraryasd blabla idk how to write
Using the Unity character controller with Photon Fusion's NetworkCharacterControllerPrototype and cannot get the player to stop sliding all over the terrain - it also starts jumping when i try to run up a hill (but not when i walk slowly). I've tried a Physic Material with friction, setting gravity, high and Raycasting to check for ground instead of using Unity CC isGrounded. No dice. Any idea what could be going on?
Photon fusion uses it's own physics engine last time I worked on it
oh seriously? it looks like it's just setting velocity
and the isGrounded comes from the Unity CharacterController which I can't seem to find how that gets set
do you have a screenshot of your game?
yeah can i post an mp4 in here? i can show the motion then
sure
that jump in there was involuntary lol
its pretty shaky too when im running
i have the character rotating based on the forward transform on the camera also as that may be relevant
You should rotate the player when you press the keys
so just bind all movement to WASD and have the camera rotate freely around him?
I had it like that before, but forward would be become backward, etc depending on which way you face the camera
Camera looks good
Add rotation to the body when you press the keys
You can think like gta 5
ah yeah I have it when you press the W key to rotate the player where the camera is facing
if you arent pressing anything it will rotate around the player
my goal was to rotate with the camera and then strafe with A and D
but as soon as i hooked up the camera to player rotation, he started ice skating everywhere and can't run up a hill
Hey,
is it possible to lerp without the update() function ?
@polar marten tyty u got me on the right path
Avatars + Avatar Masks + Layers is what i was looking for
instead of using unity editor
yes
Lerp just returns a value between start and end by percentage
So you can use it in many contexts
If you're trying to move some visual from one position to another you'd want to use it every frame though.
If you want a helper for moving things around you could check out DOTween
that is the case im looking for, is it possible to make one script to handle all the easing animation ?
Just use DOTween
I cant use DoTween , I need to build it my own
I started writing my own tweening library, it's fairly involved
But if you just want to move things, it should be easy enough
its for a client who has a package on the asset store, and doesn't want his package to be dependent on another even if it was free, doesnt wanna get involved in a complex licensing and copyright situation
How do I use an interface as a variable in a job? using one gives the error: "InvalidOperationException: VoxelGenerationJob.densityGeneratorData is not a value type. Job structs may not contain any reference types" but I don't want to be confined to a struct since they do not have inheritance
Can't you use a generic with restriction on the interface and struct?
class Tweener : MonoBehaviour {
static Tweener Instance { get; private set; }
struct Tween {
public Transform Transform;
public Vector3 From;
public Vector3 To;
public float StartTime;
public float Duration;
}
List<Tween> _tweens = new();
public void Tween(Transform transform, Vector3 to, float duration) {
_tweens.Add(new Tween {
Transform = transform,
From = transform.position,
To = to,
StartTime = Time.time,
Duration = duration
});
}
void Awake() {
Instance = this;
}
void Update() {
using var _ = ListPool<int>.Get(out var toRemove);
for (var i = _tweens.Count - 1; i >= 0; iii) {
var tween = _tweens[i];
var end = tween.StartTime + tween.Duration;
if (Time.time > end) {
tween.Transform.position = tween.End;
_tweens.RemoveAt(i--);
} else {
var progress = Mathf.InverseLerp(tween.StartTime, end, Time.time);
tween.Transform.position = Vector3.Lerp(tween.From, tween.To, progress);
}
}
}
}
what's a generic?
struct VoxelGenerationJob<T> where T : struct, IVoxelGenerationData
{
...
}
thank you so much, that is sweet of you , thank you! โค๏ธ
thx
how do you get Drawgizmos to display opaque cubes? no matter the color it's 50% transparent.
I don't think that will work for my use case, as there could need to be three generators or 5 or any number, and all these options seem to limit it to a specified number, the data I transfer into the job isn't necessarily the same, but it needs to always have some specified functions, is the only way to enable unsafe code?
once upon a time, was the square root of zero = 1? Does anyone else remember being taught that?
hey,
what is the right way to change canvas child object opacity?
Give it a canvas group component and change the alpha.
Thanks โค๏ธ
Unless the child is just a single image component, then you can just change the colour directly.
how do you code and reference post process volumes and layers in unity
ive been trying since midnight
its 2;35 now
private ChromaticAberration chromaticAberration;
private Grain grain;
private LensDistortion lensDistortion;
void Start() {
PostFX.GetComponent<ChromaticAberration>(out chromaticAberration);
PostFX.GetComponent<Grain>(out grain);
PostFX.GetComponent<LensDistortion>(out lensDistortion);
}
doesnt work
Might be a newer version or cause im using HDRP, but for my game, this is how I access it, you may only need need to change "GetComponent" to "TryGet" (technically, its not a component, they are "overrides" on a stack of the profile asset) - make sure you have your using UnityEngine.Rendering namespace, then:
public class SomeScript : Mono
{
[SerializeField] Volume fx;
ChromaticAberration blur;
LensDistortion distort;
void Start()
{
fx.profile.TryGet<ChromaticAberration>(out blur);
fx.profile.TryGet<LensDistortion>(out distort);
fx.weight = 0f;
}
}
it's another editor bug https://forum.unity.com/threads/regression-gizmos-turn-transparent-on-play.1405732/
does anyone know why this script doesn't work ONLY when I add the PlaySFX() method?
it does't matter where I put PlaySFX() in the Attacked() method :T
Did you check the console?
the console doesn't tell any errors
Is there a reason why sometimes the rotation of my object is Slerped and other times it isn't?
IEnumerator Rotate(Vector3 rot, float lerpDuration)
{
float timeElapsed = 0;
targetRotation = Quaternion.Euler(rot);
while (timeElapsed < lerpDuration)
{
transform.rotation = Quaternion.Slerp(transform.localRotation, targetRotation, timeElapsed / lerpDuration);
timeElapsed += Time.deltaTime;
yield return null;
}
}
ty for trying to help :)
why are you acting on localRotation but saving it in rotation
also for that to be a proper slerp over a set amount of time you would need to cache the starting rotation
its acting more like a move towards then a slerp due to feeding it a constantly changing rotation for slerps first arg
I believe im on the URP.
ahh ok
i'll try that
well first fix that fact its using both local and global rotation
Hi, if a gameobject has a material and mesh,
I want unity not to pack this material and mesh when Build.
how can I do this?
otherwise, yeah just cache your current rotation before the while loop, and pas that into the slerp instead of the current local rotation @paper pond
public IEnumerator AnimateBubbleText()
{
//text alpha starts at 0
for (int i = 0; i < mainText.Length; i++)
{
//make i'th character alpha 255
textComponent.ForceMeshUpdate();
TMP_TextInfo textInfo = textComponent.textInfo;
int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;
int vertexIndex = textInfo.characterInfo[i].vertexIndex;
Color32[] vertexColors = textInfo.meshInfo[materialIndex].colors32;
vertexColors[vertexIndex + 0].a = 255;
vertexColors[vertexIndex + 1].a = 255;
vertexColors[vertexIndex + 2].a = 255;
vertexColors[vertexIndex + 3].a = 255;
textComponent.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);
yield return new WaitForSecondsRealtime(0.05f);
}
}
Can anyone help me figure out why this code produces this behavior? It's supposed to updated the alpha of each character to 255 and keep it that way.
yup trying that rn
ok it works thanks @quaint rock
I think it should work the same, in requiring TryGet, it just may be in HDRP or newer version of the post process stack, that its just called "Volume" instead of "PostProcessVolume", the structure of the code should be the same though AFAIK
I tried 'Volume', says the namespace can't be found,
then did this.
PostFX.profile.TryGet<ChromaticAberration>(out chromaticAberration);```
and i get
'PostProcessProfile' does not contain a definition for 'TryGet' and no accessible extension method 'TryGet' accepting a first argument of type 'PostProcessProfile' could be found (are you missing a using directive or an assembly reference?)
trygetcomponent doesnt give any errors but then just doesn't work.
transform.localPosition = transform.parent.position - transform.position, is that right?
why, do you need to convert from one to the other
there are methods for it
numerous reasons that I don't want to spend time explaining
Huh, it may be TryGetComponent in your case then, but that should work, how are you confirming it doesnt work? If you log whats returned from out, is it null?
the post process effects just don't apply
weirdly, it wants PostFx.GetComponent etc
not PostFx.profile.GetComponent
what version of Unity are you on?
i just tested with URP 2021.2.11f1
the following worked fine for me.
Volume volume = FindObjectOfType<Volume>();
if(volume.profile.TryGet<ColorAdjustments>(out var colorAdjustments))
{
colorAdjustments.saturation.value = 999;
}
if(volume.profile.TryGet<Bloom>(out var bloom))
{
bloom.intensity.value = 50;
}
oh i might need to update unity actually... ๐
i was on a 2020 version wtf
Just pushing this
How could I add a transform.posistion to this so I can choose where the grid spawns?
call it offset
or a baseOffset if it is confusing...
and add that to the noiseMap, fallOfMap and grid?
hi guys, this honestly feels like the dumbest question, im trying to get my pathfinding implementation using dots to work, im not stuck on the dots part, im stuck on the assigning a grid to an int index.
- how to calculate the node index 'correctly' to minimise the size of the array needed
- how do i calculate the max array size when i create it?
I think these are more maths but im strugglin
private int CalculateNodeIndex(int x, int z, int yLevel, int gridSize)
{
return (x + z * gridSize/2) + yLevel;
}
NativeArray<PathNode> pathNodeArray = new NativeArray<PathNode>(_cells.Count * 25, Allocator.Temp);
I am currently making a rope system from scratch and I have ran into a problem. I'm trying to detect when a player is on a single segment to calculate which segment to move to next. The issue is that the OnCollisionEnter2D is recognizing multiple of the segments and then the player's position is rotated between every single segment, not allowing me to move. Is there anyway I can fix this? Thank you! (I can send code and screenshots if needed) : )
Anyone familiar with encryption?
public static void GenerateKeyAndIV(out byte[] key, out byte[] iv, string seed)
{
using (TAlgorithm algorithm = new TAlgorithm())
{
int blockSize = algorithm.BlockSize;
var derivedIVBytes = new Rfc2898DeriveBytes("SomeStaticIV", blockSize, 10000);
var deriveKeyBytes = new Rfc2898DeriveBytes(seed, blockSize, 10000);
byte[] ivBytes = derivedIVBytes.GetBytes(blockSize);
byte[] keyBytes = deriveKeyBytes.GetBytes(blockSize);
algorithm.IV = ivBytes;
algorithm.Key = keyBytes;
iv = algorithm.IV;
key = algorithm.Key;
}
}
I keep getting System.Security.Cryptography.CryptographicException : Specified initialization vector (IV) does not match the block size for this algorithm. when trying to use this key/iv to encrypt/decrypt.
TAlgorithm is where TAlgorithm : SymmetricAlgorithm
Why dosent this reset the bool?
It lets me shoot infinite times when I want to wait 2 seconds
You're always setting it back to false every frame when button is down.
if( ... = ...)
=
How do I fix that then
Is Input.Touch synced with EventSystem?
You'd probably want the equality operator rather than assignment operator ||==||
Or may I use them together?
Like this?
Yeah that fixed it thanks
I want to detect when a specific touch is released on a certain UI element, and I use IPointerEnterHandler and IPointerExitHandler to detect if said touch is over that UI element
Is there a code solution to gif support?
How do I know if the pointer that invoked OnPointerDown has been released?
not really a code question. but are you sure you didn't just open an empty scene?
I was working on it and it crashed
and i reopened the file I was working on
and its an empty scene
had you ever saved the scene?
and you are certain you have actually opened that scene? and not just assumed it would open automatically when you started unity again?
first, configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
second, there is no overload for Vector3.SmoothDamp that only takes 2 arguments
https://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html
so how would I fix it?
provide the correct number of arguments
there's even an example of how to use it on that page
ok cheers
Does anyone know where to get a list of C# namespaces not supported by IL2CPP?
(I recall that being a thing, if not then even better)
sorry to be a bother but ive been having this issue for a while and still havent found a solution
anyone got any ideas?
#โ๏ธโphysics message
(its in #โ๏ธโphysics if you dont want to click the link)
Thanks. Looks like there is no explicit list, but that's good. :-)
Trying to work out if I can use ConditionalWeakMap
Why does it do this? the game runns fine in the editor but as soon as i try to build i get a ton of errors?
just pseudo code but,
why is my variable of a specific class null if I don't equate it to GetComponent?
can't use the UnityEditor namespace inside of a build, the entire Editor assembly is not included in builds
make sure you put your editor-only code into a folder called Editor so it is included in the editor assembly. or wrap it in conditional compile preprocessor directives
๐ง
What else could it be?
how do you ease lerp
Does the GetComponent allows access to it's properties?
of a specific class
I kinda thought you can access the components directly after creating a variable of the class
GetComponent searches the GameObject you call it on for an instance of that component and assigns the reference to the variable
trygetcomponent
You don't access a class. You access instances of a class.
ah an object
just declaring the variable doesn't tell you which instance of the object you are referencing
You could have any number of colliders in the game. You have to tell it which collider you want to access.
gotcha, thanks for the breakdown ๐
so if I have GetComponent in a script that's attached to a specific object,
it will search that game object specifically?
yes, unless you call GetComponent on a reference to some other object
ooo thanks again
Sup! I have some issues, this is one of them. Anybody have any insight on what went wrong and how i can fix it?
- FileStream does not have a Create method https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.8.1#methods
- Do not use BinaryFormatter, it is a potential malware risk https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
Hi, I have a problem with tests. Every test passes in unity, but on CI in git one of tests has time out after [TearDown] method which actually just destroys all gameobjects. Each one of my tests is using the same [TearDown] method since all of them are deriving from the same class for tests. And I have no idea what could go wrong with this one test
couldn't really find much info googling this, but does anyone have a way to like, get a number between 1-20 based on a string?
I want to take for instance, a players character name and get an int, 1-20 based on the name
how would that even work? ๐ค
What's the logic that determines what number you get?
that's what I'm looking for ideas on
there are certainly more than 20 possible strings, how would you determine what number you get and how would you also prevent collisions?
collisions as in two strings mapping to the same number, not physics collisions with colliders
this for sure seems like some weird XY problem
https://xyproblem.info/
yeah, that is fine
two strings should map to the same number
I mean
there are only 20
please read the link i just gave and explain the purpose of what you are trying to do
Put all of them in an array, then get the index in the array + 1
What's up with VS adding using Codice.Utils when autocompleting some stuff
there really isn't much more information to give. a character will have an ID of 1-20 that will effect different things throughout the game. I want that ID to be based on their name so using the same name should give the same ID
but why do you want it based on the name specifically
well one way is you could add up the integer values of the individual characters then just % 20 it, but also the entire premise of this makes very little sense
because that is the only information that I can get, a string of their name
why is that the only information you can get? it's your game, no? just have them select a number
I thought of that but I felt that might be weighted pretty high in general
ah yes, better be picky about the solutions for an issue that makes no sense in the first place ๐คทโโ๏ธ
It's for a game I'm making in VRChat, which mostly fully uses unity/C# to make worlds/games. so the only information I have on an individual is a string of their name
weighted pretty high in general?
I'll test a few names and see what they give!
Does anyone have a simple way to clear cached info when entering/leaving play mode when domain reload is disabled?
I'd like to cache some data in SOs, but make sure that it's invalidated in each play.
I guess clearing it in OnValidate might be sufficient, but that feels like it could break.
if I did the math right, it seems to weight pretty low in general actually. most names seem to be around 1-5
show the code you used because doing it the way i suggested gets a decent spread of results if you take into account the different ways people may create their usernames
EditorApplication has some helpful events & properties for entering/exiting play mode - I'd question why you're using SO's here though, keeping persistent data from playmode is the entire point of them, and wanting to wipe data after each run is exactly what everything else does by default?
It's a cache
like cached calculations
Derived from the persistant config of the SO
I'm not sure if that answers why it needs to be in the SO - just create another object to act as the cache at runtime?
if it's supposed to only be runtime data and wiped/invalidated after exiting
I could. One option is to use ConditionalWeakTable in a static class
Which is functionally the same thing, but the advantage is I can clear it in RuntimeInitializeOnLoad
Maybe that is the best move.
I think the purpose of SOs is to have a nice interface for serialized project data, not for persisting data between runs
If you're using it for that you'll have a bad time when you build
But it sounds like you probably already know this
RaycastAll?
That will let you get all contacts on your raycast
exactly - but their purpose also extends to allowing persistent changes you make during play mode in the editor, so it's a dangerous game to use them for storing runtime caches which aren't meant to be persisted
Yeah, hence my question.
The cache won't be serialized
I just want to make sure it's cleared before I enter play mode so I can recreate it lazily
I like how everyone has a different opinion on how SO "should" be used
I mean, I guess, but it seems a bit like having a full box of different coloured crayons in front of you, picking a red one, and then saying "how can I change this so it isn't red"?
anyway - I'm sure EditorApplication will have what you're looking for ๐
well I haven't done anything yet, I'm asking a question here
lol
I am using SOs to store configuration data for weapons and projectiles
In answer to your question
And I am asking what a good way to store derived data from that config is
Im also under the impression that persisting data with SO's is problematic and definitely not "the purpose" of them
oops lol
I wrote the wrong thing
I mean persisting data in the build
in the project
wait that is what I wrote
...
You did mention the build here :D
Im agreeing
Haha, I misread my own comment
Yes. :-)
Yeah, doesn't make sense to persist data between runs
It will just make your project run differently in editor to build
Well, I would say that was the quintessential unity discord experience.
Asked a question, got told I was wrong for asking until the question got pushed above the fold lol
Relatable
did some more digging and came up with this. it seems to work well! cs public void GetID() { string name = "mimi"; int total = 0; foreach (char c in name) { int letterValue = (int)c; total += letterValue; } playerID = total % 20; Debug.Log("ID is: " + playerID); }
I'm not really sure how char c and (int)c works? but testing many names seems it does give a good spread!
that's exactly what i was suggesting. a string is made up of multiple characters (or char) and a char is a character represented internally by an integer so you can cast it to int to get that integer value
you'll want to +1 that playerID though unless you want values from 0 to 19 instead of 1 to 20 (inclusive)
ah ok, 0-19 is fine. thanks for the help! sorry if the question wasn't very clear
answering your question was the first thing I did, though questioned your original suggestion of using SO's to cache your data as it sounded like an XY problem ๐คทโโ๏ธ
the way I tested it at first was really dumb btw. I didn't know about a string with characters being represented internally by integers so I literally sat there and was like "a = 1 b = 2"
Silly question. Is there a way to do a one line if statement without an assignment? It's possible in some other languages but maybe not in c#?...
I can do this:
_ = correctAnswer ? AnswerIsCorrect() : AnswerIsIncorrect();
but only if functions have a return value.
I mean it's so seductive to do it in one line, so natural, instead of 6 or 4 with standard if statement. Very silly question, i'm sorry :D
no, ternary operator can only be used with assignment
you could just do if(correctAnswer) AnswerIsCorrect; else AnswerIsIncorrect; all in one line if you must have one line
Anybody got any ideas on what kind of object reference i could use?
You'll need to share code.
I attached the code as images
also configure visual studio !vs
Hi there. Does anyone know how to get the name of a specific sprite assigned to a SpriteRenderer that's been taken from a spritesheet? I've tried using sprite.texture.name but that only tells me the name of the sheet itself and not the sprite within the sheet that the SpriteRenderer is using. Any ideas how I can access that name via code? Thanks! ๐
!ide
seems the bot died
I thought there was a bot
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
๐ 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.
oh there it goes
there we go
Anyway, the answer is that you need a reference to the object instance with the data you want to save
for what purpose
Your code has a class before the .
IT's just hard to tell there's a compile error because you haven't set up your IDE, which you should do before asking more questions.
@somber nacelle Initially I assign a sprite to the renderer. This will later change in game and I need to remember the original sprite assigned
Save a reference instead of the name perhaps?
just store the reference in another variable then, don't rely on the name of the sprite
I haven't used spritesheets much
OK. Any quick tips on how I'd do that?
Sprite _prevSprite;
void SetSprite(Sprite sprite) {
_prevSprite = _spriteRenderer.sprite;
_spriteRenderer.sprite = sprite;
}
void RestoreSprite() {
_spriteRenderer.sprite = _prevSprite;
}
if I have reference a resource in MonoBehaviour, how to ask unity not to pack this resource when Build?
I believe Resources are always built into the game. The point is theyre always available even when not referenced
Are you talking about the Resources folders specifically?
not in the Resrouces folder
Nvm then
such as a model or texture
I want something like this :
[NotPackToGame]
Texture tex;
but why? ๐ค
surely if your code relies on a reference to something you would want that object to be included in the build, no?
because I use a different thing in game
for example?
Im on mobile, boxfriend go at it
i'm not entirely sure how well it plays with including/excluding assets from a build though. but if you are normally assigning the variable in code when in a build, just mark it as NonSerialized only for when not in the editor. or if you don't even use that variable in the build then just get rid of the entire variable in the build with the preprocessor directives
Could have a build process to find it and remove it
How to not make this lerp the position?
Right now it makes the other object go to the next one at the given speed ignoring the distance between.
private void Update()
{
direction = nextTrackLink.transform.position - transform.position;
float lSpeed = speed * Time.deltaTime;
transform.position += lSpeed * direction;
}
you probably want to normalize the direction
but also i don't understand what you mean by "at the given speed ignoring the distance between"
No matter the distance between transform.position and nextTrackLink.position it takes speed amount for transform.position to reach nextTrackLink.position.
normalize the direction when you multiply it by lSpeed
Does Unity Object instance ID has any sort of NaN number?
Some value that is never going to be assigned to instanceID of Objects?
probably not
i remember this forum post had more info on instance idโs, it might have useful info, not sure
it does mention briefly how they are assigned
Hi, just wondering if someone could point me in the right direction. Im wanting to code a minigame where you clean an object, bit like pressure wash sim I suppose. I know id be needing a dirt map, and to use a brush texture to remove that texture, but I cant find anything to help with being able to code this, Ive never worked with shaders before.
not much of a value for my use case, but I think simple description hints me that it can't be 0
Hey, so i want to make a system, that when ur mouse is near a object that have "Interactable" script, it sets the ui position to this object position. I already tried doing Ray tracing with Dot product, doing sphere Overlap and i tried converting all of the objects to screen space and checking which is the closest to mouse position but that didn't work, right now im using dot product and ray tracing and it works but i want to disable ui when the dot product doesn't detect any object with interactable script
My current script (inside update):
float closest = 0f;
Ray ray = playerCameraInstance.ScreenPointToRay(Input.mousePosition);
Interactable[] interactables = FindObjectsOfType<Interactable>();
foreach (Interactable interactableObj in interactables)
{
Vector3 vector1 = ray.direction;
Vector3 vector2 = interactableObj.gameObject.transform.position - ray.origin;
float lookPercentage = Vector3.Dot(vector1.normalized, vector2.normalized);
if (lookPercentage > 0.9f && lookPercentage > closest)
{
closest = lookPercentage;
interactionUI.position = playerCameraInstance.WorldToScreenPoint(interactableObj.transform.position + Vector3.up * yOffsetInteraction);
}
}
How monebehavioure can call start awake and other methods when i set there access modifier as private, does that mean they are called using reflection?
Those are unity event functions. They are special methods. If you add them in a MonoBehaviour script, they will get called . . .
what does "special" means in term of c#? lets say i want to write game engine too, can i go and modify CLI? no! even c# features are written in clean c# and how does unity make it work non clean way
by non clean i mean that private methods can't be called by parent class in pure c#
Via Reflection and source generators you can modify and inspect the source code at compile/runtime.
Yes, by reflection. Unity is built in c++ but it's core functionality is exposes (wrapped in a layer) the .Net API to provide c# functionality to its users . . .
Hey guys does anyone know the API where i can add bone transform keys to my avatar pragmatically
I know we have this but this doesn't let you add bone transform keys
Avatar avatar = AvatarBuilder.BuildGenericAvatar(activeGameObject, "");
Or will it do this automatically?
YO WHERE DID TIME.DELTATIME GO????
WAIT NVM
lol
dw
I forgot I had a class called Time
bone transform keys?
Yeah so im making a avatar mask for various bones i want to move
Main bones which are not shared, so i can play different animations on them
My animator will have these layers
with the Mask created and synced to base layer
then override animation controlller can do the rest of the job
๐ฆพ
great time to figure out how to save masks
actually im just gonna point the masks manually to assets
okay just to confirm you are not
creating keyframes manually anymore right?
when you said bone transform keys, you meant the mapping from the transform hierarchy to the animation hierarchy*?
which is what an avatar is ๐ so my expectation is it should be configurable somehow
i am not
๐
I tested the masking and it worked
but i need to generate the mask keys with a script
in the editor instead of manually doing it for every model
If multiple buttons (in the UI) all trigger one function in a script, how can the function know which button has been pressed? Do I have to make multiple functions for each button that each call the function that does something with an "ID" for each function called by the buttons?
Is this an appropriate place for me to ask for some feedback on some code that I've written or where is a good place to do that?
got it, that makes sense to me
sorry i misunderstood
pass an argument into the function that corresponds to which button was pressed
if you are using the inspector to wire up your buttons
you can pass a single argument
Yes, do I do that with the second option in my message?
you can post it here. kindly add a question though
no, you can use one function
i don't understand
why you would organize it like
button 1 all go into -> function ---> function 1
button 2 function 2
button 3 function 3
button 4 function 4
public void ButtonBody()
{
ChangeTab(0);
}
public void ButtonMechanic()
{
ChangeTab(1);
}
public void ButtonGround()
{
ChangeTab(2);
}
public void ButtonInput()
{
ChangeTab(3);
}
public void ButtonOutput()
{
ChangeTab(4);
}
public void ButtonMisc()
{
ChangeTab(5);
}
public void ChangeTab(int buttonID)
{
//code here
}
yeah
why don't the buttons directly call changetab
if you're wiring it up in the inspector
you can pass the argument in the inspector @floral coral try it
I don't know how
- that's why I came here
simply choose changetab
instad of buttonground
you should observe you can choose ChangeTab in the dropdown for the on click part of the inspector for your Button component
I've been working on a system to handle things like daily schedules for NPCs and other things that make sense to happen in "Game Time" rather than real time. I don't have any kind of formal background or a lot of experience in coding and in this system am using some things I'm not super familiar with (like delegates and actions). I was really just hoping maybe I could get some general feedback on it to see if it seems generally sensible.
Here is the script for the main TimeManager system: https://paste.ofcode.org/ZNvUii5m6FxLWe8XifYHNJ
And a small script I'm using to test it currently to show how it can work: https://paste.ofcode.org/As6ZRkyLQGycPgmrePdSnM
I would really appreciate any feedback anyone can give me honestly.
I have such a tween from DOTween:
var tween = transform.DOMove(destination, (destination - transform.position).magnitude / speed);```
How do I change its duration midway? (i.e. in update)
I mean I want my character to get a sudden speed boost
U need to make a new T and use that in AddComponent
Modinstance type will be inferred
Your using a Type T in AddComponent right now
Why not just make it take a parameter of type Mod?
Oh wait I see what youre trying now
hey, how do you find the game_id of a project?
i think you should consult the docs for this one
hmm i ll try
will game time ever be longer than real time in one session of your game?
I have been told my game could use some more "bounce". My project is already using DOTween, but someone recommended to me that LeanTween would be good for this and showed me a decent looking tutorial
1)is it bad form to import both DOTween and LeanTween into a project when they really do the same thing
2) does anyone have thoughts as to which would be better (or potentially a 3rd option) for adding some 'bounce' to a game?
If you wanna see it (this version only works in Full HD 1920 * 1080)
https://galahadgaming.com/Games/Builds/
Is Mod a MonoBehaviour?
By real time do you mean Time.time? In this context game time will be time within the game, so yes it will pass at a rate faster than real world time.
Yes. So I guess there's no way to generate it on the fly like this?
Once I attach the component I can just do mod.BindToUnit
Or do you mean something else like am i saving it somewhere and loading it in?
across multiple sessions, because also that.
okay
i haven't looked at your code yet
but that can be pretty tricky
even people with a formal programming background, like me - when i first learned how to do this correctly it wasn't at all obvious
I guess the only way to do this is to have a library of prefabs (one for each type of Mod) and then have it pull from that
is your game like an animal crossing game?
You would have to use System.Type and AddComponent (non generic overload) with that, but I'm not even sure if that would work either
What's the normal way to do something like this?
Probably coupling the mods with an enum
@polar marten I mean I haven't currently put in a way to save and load the time, but the actual saving i can handle since i'm storing it as a long, so it would just be a matter of putting in a method my save manager can call to set the property currentTime, I believe.
so is the game like an animal crossing game?
And then just pulling from a list of prefabs to add component with?
or some kind of rpg, where characters move around in real time and do stuff?
No this is an rpg
or having a big switch statement
Maybe a Dictionary<MyEnum, GameObject>
Hi, how can I change the default position of the content of Scroll Rect? Green area is the Panel with the Scroll Rect component and red area is content of it. I would love to have that content on the top of green area but I have no idea how to do that. Does anyone have any ideas?
is it possible for your npcs to have done stuff while the player has not been playing @steady thicket ?
I'll buy the goose right now!!
@steady thicket the punchline to all of this is, what is the design space of what you actually want to do?
@hard sparrow Be aware that dictionary isn't serialized by default so you'd need to generate it or use SerializableDictionary for example
Or hard code it but thats less flexible
@polar marten well my plan is that each will have a schedule of where they are at any given time, when a scene is loaded they'll be placed where they should be, but nothing will actually happen unless the scene is loaded. Does that answer your question or did you mean something else?
Yes I was actually already using that method for something else. Just wanted to see if there was a more on the fly way to do it
then as the game plays they will move to different places and do different things as time progresses
Hey guys, So i created a pause menu for my 3d game. Everything is working fine but when I press ESC the Pause Menu pops up but my game doesnt freeze I can hover around by my mouse and my character looks here and there. Here is my Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class pausemenu : MonoBehaviour
{
public static bool GameIsPaused = false;
public GameObject pauseMenuUI;
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if(GameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
public void Resume()
{
Cursor.lockState = CursorLockMode.Locked;
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
GameIsPaused = false;
}
void Pause()
{
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
GameIsPaused = true;
Cursor.lockState = CursorLockMode.Confined;
}
public void Loadmenu()
{
GameIsPaused = false;
Time.timeScale = 1f;
SceneManager.LoadScene("menu");
}
public void QuitGame()
{
Debug.Log("Quitting Menu...");
Application.Quit();
}
}
following their schedule
Put your code in a paste site !code
Bot is slacking, rip commands
mb
But I'd also like to implement some other things that make sense with this system, examples could be things like the player is well rested for 4 game hours or sick for 3 game days or something.
here is an example of interesting npc rpg gameplay:
// a villager who gathers berries to sell them at the market
public async Task BerryGathererLoop() {
while (!Dead()) {
try {
await WakeUp();
var berries = await FindBerries();
await GoTo(berries.position);
await Gather(berries);
var market = await Find<Market>("Market");
await GoTo(market.position);
await market.Trade(this, berries);
// in this loop I go home
await GoToSleep();
} catch (OperationCancelledException) {
// this goes to another loop where
// the villager checks if he's hungry, sleepy,
// low health, etc. and tries to resolve
// those exceptional issues. we assume if
// the villager fails here, the villager died.
await TryToStayAlive();
}
}
}
@steady thicket making this piece of code work is hard
but on the other hand, you know exactly what the npc is going to do. it's very expressive
i'm not saying you have to do this. but if your design space - the scope of what you want to achieve - is "all possible RPG behaviors" - this is hard
that's why i am asking what you want to do
@polar marten Well this particular system isn't about behavior, it's purely about keeping track of time and calling methods when it's at least a certain time. I understand what you mean about how things can get very complicated quickly, though. My system does what I want it to do currently in the tests I've done, I just don't know if I'm way out in left field or not with how I'm achieving this.
Just looking over the code since I posted it I've noticed a couple of weird ways of doing things that are left over from earlier iterations of the code here and there and a few naming inconsistencies, I went over it a few times before posting but still missed a couple of things it seems, so ignore that kind of stuff if you do look at it lol.
Hi labs, this is my script to get rewarded by passing the points which are need it to activate the new character. How can i set in that user, which download my app, starts from beginning? Because if you download my app right now you have the new character but thatโs wrong. Everyone should start from zero, so collecting the limit of points to activate
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
am I using clamp wrong? Output always shows the y velocity as 0 and player falls very slowly
velocity will be negative as this function is run when player has reached highest point of jump
Check component
your minimum and maximum parameters are flipped
is there a way to have new sprites/textures automatically do all the 2D pixel perfect settings, like setting the pivot for individual sprites? i have the preset setup for textures but is there a tool or scripting solution something?
What exactly is loadsceneasync? i know it loads in the background but how specifically does it load? does it just function like loadscene or does it load the data and then you can actually like "load" it to where its visible. Also if I have a scene queued up with loadsceneasync wont it just hog up memory?
im not sure if it loads pieces of the scene one by one and you could theoretically do something in between each gameobject on the main thread while its loading, but it drops everything into the scene automatically
typically you use the progress variable and wait for it to be over, but you can do stuff like animating a loading screen on the main thread without the program freezing
im not sure what you mean by hogging up memory here
if you use Additive mode it will layer the scene on top of any scenes already loaded, if not then i think everything gets unloaded apart from DontDestroyOnLoad stuff, generally i think thats it but i might be inaccurate in some way
Thank you!
i move my character with navmeshagent.move and i have objects that follow player
but when i increase lerp speed of objects its jittering
its like very laggy
i tried to lerp in all updates but still laggy like it updates immedialty every 10 frames or smth like that
code?
its your interpolant, t parameter
t is how far along on the line between A and B you should move, giving a speed will not move the same distance, you can calculate T by doing (target - current) / speed * time.deltatima
You just want something like this, no?
float timer = 0;
float multiplier = whatever;
void Update() {
timer += Time.deltaTime;
}
const int SecondsInMinute = 60;
const int SecondsInHour = SecondsInMinute * 60;
const int SecondsInDay = SecondsInHour * 24;
public float ScaledTime = > timer * multiplier;
public int Seconds => Mathf.FloorToInt(ScaledTime);
public int Minutes => Mathf.FloorToInt((ScaledTime / SecondsInMinute) % 60f);
public int Hours => Mathf.FloorToInt((ScaledTime / SecondsInHour) % 24f);
public int Days => Mathf.FloorToInt((ScaledTime / SecondsInDay));```
Time.time and deltaTime will both freeze when setting time scale to 0
if you want to not have that happen you use Time.unscaledTime and Time.unscaledDeltaTime
sorry i had to write that quickly, its actually t = (target - current).magnitude / (speed * Time.deltaTime)
wait im an idiot
there it is, magnitude
its even worse now
i mean yeah i added magnitude earlier but
i dont think t is okay with this
its jittering now when followspeed is less than before
its actually teleporting
uhhh
not even lerping
wow i really keep messing that up off the top of my head thats my bad
i dont think using distance here makes sense
the ratio is amount traveled per frame / total distance
i gave you the inverted ratio so flip it
am i misunderstanding your code then? you want to move from current position to target position over time?
t = (speed * deltaTime) / (target - current).magnitude is what i use, my bad
no you are correct
still doesnt work correctly
I am making a UnityWebRequest to the following local url (it's a simple server manager) and checks to see if a room exists and if so returns the port to connect to - https://localhost:7106/Server/Find?roomCode=ABCD the url works perfectly everytime in something like PostMan, but Unity seems to be sending it weird. Are query parameters not supported? If not, what do you recommend?
Should be fine just make sure you're:
- using the same HTTP method (GET / POST / PUT etc)
- providing the same headers
and maybe explain what you mean by "Unity seems to be sending it weird"?
@leaden ice I'm sending it via
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
When sending via UnityWebRequest, roomCode will randomly contain a ? at the end of the roomCode variable and it shows up in the Console.WriteLine step
what is the value of uri?
print it
Debug.Log($"URI is: '{uri}'");```
sorry for messing up before but that final formula for T is correct, that part should be working now but the problem must be from somewhere else
@leaden ice I printed it with and it outputs https://localhost:7106/Server/Find?roomCode=PGXV as an example
The Debug.Log occurs the line before the Get UnityWebRequest
can you log it the way I did
with ' ' surrounding it
you might have some extra weird invisible character at the end or something
So i am getting the null reference exception and it seems camera.LookAt isn't working with the Cinemachine Free Look Camera. How can I swap the Look At Target?
@leaden ice This is the output immediately before sending (with UnityWebRequest) and the Searching db is the immediate check on the webapi side outputting the roomcode variable
that is... strange ๐ค What are you using for the server, ASP.Net?
Yep, trying it with a non-query parameter /shrug
Are you getting that URI from an Input Field? If yes you might want to make sure the variable is of type TMP_InputField, and especially not a reference to the underlying Text it uses to display your input, as it adds an invisible character at the end.
You should just use https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=net-7.0 so you don't have to implement all this yourself
if you really want real months/days/years etc
otherwise you will be in hell dealing with the logic and the exceptions
@simple egret mm, so this should be changed to
var roomCode = RoomCode.GetComponent<TMP_Input>().text;
I am having a very odd problem: I load game object through AssetReference (addressables). Instantiate it. Aaaand, it's Awake is not called, Quite literally.
var operation = _editorPrefab.LoadAssetAsync<GameObject>();
await operation;
if (operation.Status is AsyncOperationStatus.Failed) throw new("Failed to load editor prefab");
var editor = Instantiate(operation.Result);
is there something I don't know about dynamically loaded assets?
@simple egret @leaden ice That did it. Thanks for the help both of you!
time scale is irrelevant. You would just do this:
TimeSpan elapsedTime = TimeSpan.FromSeconds(timer);
DateTime currentTime = startTime + elapsedTime;```
then you can do currentTime.Days etc..
timer is a number you keep track of and increment etc
so the scale would be already dealt with there
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("bowlingpin"))
{
Destroy(collision.gameObject);
}
}
I have this script attached to the ball and if the ball collided with anything i check the tag
but on the editor it gives me the error that the Tag : bowlingpin is not defined.
Hi,
is it possible to run a function when enum value changes ?
using a property you can do anything you want in response to your variable changing
you have to have defined that tag in the editor
apparently you haven't
yes i did a typo, my bad
could you give me an example on how to use property on an enum ?
the type of the variable is irrelevant
Thank you so much , I dont know why I thought it wont work
Can you share with me your code for a ball in basketball game? There are various guides but most of them dive into theory which I really do not need
if all you need is a bouncing ball you dont need any code for that i think just physics component
Just apply a physics material to the collider with a high bounciness like Algo said above
No physics allowed for it. Anyway just fixed a bug and now it's working
I have been working on a terrain generator and I have got it to work but the only issue is that I can't seem to find a way to move the tilemap so the terrain generates elsewhere.
Anyideas?
Here is what I have somewhat tested so far
//gets tilemapย ย //Tilemap tilemap = GetComponent<Tilemap>();ย ย //BoundsInt size = tilemap.cellBounds;ย ย //TileBase[] allTiles = tilemap.GetTilesBlock(size);
and this is the only source that I found helpful
https://forum.unity.com/threads/tilemap-tile-positions-assistance.485867/
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap-origin.html
Unity - Scripting API: Tilemaps.Tilemap.origin
How can you set a LookAt Target for a Cinemachine FreeLookCamera via script?
Really stupid question but is there a simpler way of doing this rather than having an almost instant invoke?
Without the invoke, the RB constraints are only set to none.
{
if(timeToFall < 0)
{
theCageRB.constraints = RigidbodyConstraints.None;
Invoke("FreezeRB", .1f);
Destroy(gameObject);
}
}
void FreezeRB()
{
theCageRB.constraints = RigidbodyConstraints.FreezeRotation & RigidbodyConstraints.FreezePositionX
& RigidbodyConstraints.FreezePositionZ;
}```
Your Invoke is not going to run since you are destroying the GameObject your script is attached to
also not sure I really understand what you're trying to do here
how do i name my script to other scripts?
like, if This Collides with this Script 001 is Disabled for X amount of time
how to add [Range(0,100) to a float's property ?
is it even possible ?
public float someFloat;
[Range(0, 100)]
public float SomeFloat
{
get{ return someFloat;}
set{ someFloat= value;}
}
I think range just for items shown in the editor, and properties are not shown in the editor ever.
Yeah, add the attribute to the field
You can also use an auto-property for that:
[field: Range(0, 100)]
public int SomeValue { get; set; }
field: tells the compiler to add the attribute to the auto-generated backing field
warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored.
You're not applying the attribute to a property
Properties have accessors { get; set; }, make sure you've put it on the right one
that is what I did
public float someFloat;
[field: Range(0, 100)]
public float SomeFloat
{
get{ return someFloat;}
set{ someFloat= value;}
}
Works fine for me
Ah, because it's not an auto-property
You have your own backing field declared. In this case just put the attribute on that, without the field qualifier
Does anyone know how to get ruletilemaps working easily for a 2D platformer
idk why but i find it confusing
im trying to write some code when a scene changes. but i am not getting EditorSceneManager.activeSceneChangedInEditMode to trigger. what exactly is it that triggers it?
Having a little trouble wrapping my head around what project on plane does with a direction
is this
// is this
_velocity = Vector3.ProjectOnPlane(_velocity, Vector3.up)
// the same as
_velocity.y = 0;
_velocity = _velocity.normalized;
It basically flattens a vector on a specific plane
did u mean like my original code that didnt work ?
error :Attribute 'Range' is not valid on this declaration type. It is only valid on 'field' declarations.
public float someFloat;
[Range(0, 100)]
public float SomeFloat
{
get{ return someFloat;}
set{ someFloat= value;}
}
So yes? 
Yep, the same
Assuming _velocity is normalized when it starts out
Cool
thanks
I found it in a component I wrote 2 years ago 
Hm I don't think ProjectOnPlane normalizes though, you'd have to do it yourself
Noted
But it's really useful when the plane isn't flat on one axis. Say you want to flatten on your local up, whatever your rotation is
Go do that by modifying the velocity directly, good luck
could you give me an example? I still couldnt make it work :S
Something like this will do the trick
[Range(0, 100)]
public float _value;
public float Value
{
get => _value;
set => _value = value;
}
Ignore the contents of the property accessors, I made it shorter but your version with the return in the getter will work exactly the same
There's no real reason for the field/property separation there, though, so it could all just be shortened to
[field: Range(0, 100]
public float Value {get; set;}
Yeah exactly, just let the compiler do the work
Thanks for example,
@simple egret thank you
Yes both of them worked smoothly <3, however, the desired result wasnt reached, I wanted to run a function when the value of float change by the editor, that is the whole reason of adding property to it in the first place, and the slider is just to make it look nicer.
I have noticed right now with or without the slider when I update the float value by the editor , the debug doesn't run.
public float someFloat;
[Range(0, 100)] // with or without , it doesnt matter
public float SomeFloat
{
get{ Debug.Log("GET was fired"); return someFloat;}
set{ Debug.Log("SET was fired"); someFloat= value;}
}
Yeah it bypasses the property
Getters and setters won't be executed by the editor
You can use OnValidate() message to do your validation in that
The Unity editor is not aware of properties, only fields
I'll look it up ,MonoBehaviour.OnValidate() Thanks โค๏ธ
Anyone have any idea how its possible for the Raycast or spherecast to find a point here? Notes: swingsActive is a list containing two booleans. Predictionpoints is a list of two positions of sphere's which show possible locations to attach a grappling line to. Code: https://hastebin.com/share/efiqanifij.csharp
BTW: the anchor is not touching the ground, it's floating in the air. I tried codee-beginner before but it seemed like everyone was busy
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I should note that the point aimers are facing in front of the player, who is facing the black columns
Is it normal for "earth gravity" i.e. 9.8 meters/second to feel too low? Or is something wrong with how I'm calculating it?
I'm inclined to feel like I must be doing something wrong, but it's so simple...
var verticalVelocity = _velocity.y;
verticalVelocity -= (GravityDownForce * Time.deltaTime);
verticalVelocity = Mathf.Min(verticalVelocity, -TerminalVelocity);
_velocity = horizontalVelocity + (Vector3.up * verticalVelocity);
_controller.Move(_velocity * Time.deltaTime);

If I do 2x gravity (19.6m/s) it feels pretty much exactly how I'd expect 
Oh I just realized I'm doing terminal velocity wrong, but I don't think that matters here
๐
Log the velocity ๐คทโโ๏ธ
Print the velocity..
What am I looking for in the velocity specifically?
Like the physical experience of falling is a direct map of the velocity
See if it's what you're expecting.
I can tell from the fall that it is not, acceleration feels much too 'airy' like I'm in the moon, but I'm using the 'real world' gravity value 
But if I double gravity then it feels about perfect, which suggests my algorithm is wrong somehow... 
Bot is buggy
got it! thanks :))
hey guys ! I have an enemy who follows the pink player using AI pathfinding (A*). I used an A-star package but coded the AI. For the maze, I used 2D square walls. As shown in this video, the enemy takes a long time to find a path to the player. Can anyone check the code and let me know if there is anything got to do with the 2D square walls? Or is it something with the waypoints. The enemy goes ahead and then stops
!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.
how do i unsubscribe from this?
playerInputs.movementActions.Reload.performed += ctx => Reload();
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class EnemyAI : MonoBehaviour
{
public Transform player;
public float speed = 200f;
public float nextWaypointDistance = 3f; // Stores the next way-point distance
Path path;
int currentWaypoint = 0;
bool reachedEnd = false;
// Referencing the seeker script
Seeker seeker;
// Referencing the Rigid Body 2D script
Rigidbody2D rigidBody;
void Start()
{
// Finds the two components on the enemy object
seeker = GetComponent<Seeker>();
rigidBody = GetComponent<Rigidbody2D>();
InvokeRepeating("UpdatePath", 0f, .5f);
}
void UpdatePath()
{
if (seeker.IsDone()) // If it is not currently calculating a path
seeker.StartPath(rigidBody.position, player.position, OnPathComplete);
}
void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0; // Reset the current way point
}
}
void FixedUpdate()
{
// Checks if there is a path for the enemy to follow.
if (path == null)
return;
// Checks if the enemy has reached the end of the path.
if (currentWaypoint >= path.vectorPath.Count)
{
reachedEnd = true;
return;
}
else
{
reachedEnd = false;
}
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rigidBody.position).normalized;
Vector2 force = speed * Time.deltaTime * direction;
// Adding the force to the enemy
rigidBody.AddForce(force);
float distance = Vector2.Distance(rigidBody.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
}
}
This is my enemy AI code
.
how call material texture name in setTextureName in script? i tried the name how its in Editor ("Base") and in shaderfile ("_MainText") and for both it throws error "Material does not have texture property x"
hi ,
is it possible to make a float range with dynamic minimum and maximum ?
int min =0;
int max = 200;
[Range(min,max)] // instead of [Range(0,200)]
public float value;
Using const only
const int min =
So no not really "dynamic"
no because it has to be outside declared function, and to have variable declared outside function it needs to be const
and const cant be changed during runtime
Variables declared outside of functions don't need to be const. Everything else you said is true
thanks โค๏ธ
Cache the lambda and subscribe/unsubscribe that.
how do i do that?
You'd probably not want it to be a local variable though..
I'm getting this error after destroying an object with this code
playerInputs.movementActions.Fire.performed += ctx => FirePerform();
i'm getting the error because i'm not unsubscribing before destroying the object right?
Correct, and subscribing with a lambda like that ensures you will not be able to unsubscribe
Likely so, else you're invoking while there are no actions subscribed (I don't recall the behavior of the New Input System off the top of my head)
can you explain how to use that in my case? because i'm really confused by it
I've given code. Are you asking me to give you code relative to your use case?
why is started and performed almost instantly executed at the same time as each other, started always happens first but there's not even a single frame of time before performed is executed
it just means i cant run something between started and performed which is annoying
//Reference the Lambda that wraps a regular method without args:
Action<InputAction.CallbackContext> reload = (ctx) => Reload();//Not using the Callback Context...
...
playerInputs.movementActions.Reload.performed += reload;
It depends on the interaction you have set on your input action
If you use a hold interaction for example you need to hold the button that much time before performed happens
wouldn't that work the same as cancelled?
or would performed still execute while you're still holding the button but slightly delayed?
The whole point of the hold interaction is that it performs after n seconds of holding
Canceled is when you release
Or have private functions that fit the signature yet throw away the callback context... cs private void ReloadCTX(InputAction.CallbackContext _) => Reload(); ... playerInputs.movementActions.Reload.performed += ReloadCTX; ... playerInputs.movementActions.Reload.performed -= ReloadCTX; @pearl trench
Where _ would be our throw-away/discard placeholder https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards
thanks for your help man
but i think there's another reason why i'm getting the error
I tried that and the unsubscribe worked but still getting the error
Anyone have any idea how its possible for the Raycast or spherecast to find a point floating in the air? Notes: swingsActive is a list containing two booleans. Predictionpoints is a list of two positions of sphere's which show possible locations to attach a grappling line to. Code: https://hastebin.com/share/efiqanifij.csharp
BTW: the anchor is not touching the ground, it's floating in the air, and the player is facing torwards those black columns.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Unclear what you mean? You can log the hit gameObject by submitting it as a parameter.
Debug.Log("Hit", gameObject);
If you do this, and submit the object you hit. You'll be able to click on the log in the output console and it will mark what you hit in the hierarchy.
Very confused, my jumpindex increases by 1 the first time I call Jump, but if I call jump again it wont increment? It'll increment again if I've called jump twice though
how will it know what my hit gameObject is?
like where must I put it for it to know that
or is "Hit" built into raycast?
Your raycastHit structs has the information
What you wrote does not make any sense to me. Simplest to use a breakpoint to see what is going on when you call it?
Sorry Mr. Jaws, I'm still a little confused. If I used gameObject in the debug, wouldn't it just give me the gameObject of whatever contains the script?
it doesn't increment the counter the second time I call it
but does it every other time
What do you mean call? Do you call it manually? Or do you mean when you're pressing a button?
pressing a button
So pressing the button twice does not produce two logs?
