Download

Accessing another player's variables

Well, the title might be a little confusing as I wasn’t able to think of one relating to this topic. So my question is:
How to access a different player’s variables in a multiplayer game?!

What I want to actually do is on hitting another player with a particular projectile will change one of it’s variable like on hitting with an ice projectile, disable the input.

Please help!!
Thanks in anticipation!!(Formal and Casual at the same time)

When you hit the player with a projectile you want to get the AActor of the player you hit and cast from AActor to your player class, like this:



AMyPlayerCharacter* player = Cast<AMyPlayerCharacter>(hitActor);
if(player != nullptr) //Perform a nullcheck since you might hit something other than a player (like a wall)
{

}


To know when you hit a player you’ll need a delegate

Put this in the constructor of your bullet class:



    //create collider
    collider = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere collider"));
    collider->InitSphereRadius(10);

    //setup collision
    collider->SetSimulatePhysics(true);
    collider->SetCollisionEnabled(ECollisionEnabled::PhysicsOnly);
    collider->SetCollisionProfileName("BlockAllDynamic");
    collider->SetUseCCD(true); //Required for fast moving objects, like bullets

    //setup collision notifications
    collider->OnComponentHit.AddDynamic(this, &ABullet::OnHit);
    collider->SetNotifyRigidBodyCollision(true);


Add this to your bullet cpp file



void ABullet::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit)
{
AMyPlayerCharacter* player = Cast<AMyPlayerCharacter>( hitActor );
if(player != nullptr ) //Perform a nullcheck since you might hit something other than a player (like a wall)
{
//Here you can access your player's health variable, for example
//Like player->health -= 10;
}
}


Don’t forget to add this to your bullet header file



UFUNCTION()
void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit);


I hope I helped you :slight_smile:

Thanks for all this help, man. I had actually given up on getting an answer for no one was replying. You rock. Even cleared the cast function to me. Again, you rock!!